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

how to access THIS in cordova plugin with IONIC

我正在尝试使用 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");
            })
        })
    }

当您使用 function 关键字定义回调时,this 的含义会发生变化。防止这种情况的最简单方法是使用 粗箭头 符号来定义函数:

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?