如何使用IONIC在cordova插件中访问THIS

问题描述 投票:0回答:1

我正在尝试使用cordova插件实现apple-sign-in方法,并将凭据设置为firebase。

我实际拥有的是:

    constructor (
        public afAuth: AngularFireAuth,
        public afs: AngularFirestore,
        @Inject(FirebaseApp) firebase: any
    ){
        this.firebase = firebase;
    }

    loginApple(): Promise<boolean> {
        return new Promise((resolve, reject) => {
            cordova.plugins.SignInWithApple.signin({ 
                requestedScopes: [0, 1] 
            }, function(succ){
                var provider = new firebase.auth.OAuthProvider('apple.com').credential(succ.identityToken);
                this.afAuth.auth.signinWithCredential(provider).then(result => {
                    //--> it seems the problem is here, because variable THIS is not available in the cordova plugin without a ionic-native wrapper <--
                }).catch( error => {
                    reject( error.message || error );
                })
            }, function(err){
                reject("Apple login failed");
            })
        })
    }
javascript firebase cordova-plugins ionic4
1个回答
0
投票

this的含义在使用function关键字定义回调时会改变。防止这种情况的最简单方法是使用fat arrow表示法定义函数:

return new Promise((resolve, reject) => {
    cordova.plugins.SignInWithApple.signin({ 
        requestedScopes: [0, 1] 
    }, (succ) => { // change is here
        var provider = new firebase.auth.OAuthProvider('apple.com').credential(succ.identityToken);
        this.afAuth.auth.signinWithCredential(provider).then(result => {
        }).catch( error => {
            reject( error.message || error );
        })
    },(err) => { // changed here too, for consistence
        reject("Apple login failed");
    })
})

另请参阅有关问题原因和其他解决方案的此答案:How to access the correct `this` inside a callback?

© www.soinside.com 2019 - 2024. All rights reserved.