how to access THIS in cordova plugin with IONIC

微笑、不失礼 提交于 2020-01-22 02:48:05

问题


i am trying to implement the apple-sign-in method using a cordova plugin and set the credentials to firebase.

what i actually have is:

    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");
            })
        })
    }

回答1:


The meaning of this changes when you define a callback with the function keyword. The simplest way to prevent that is to use fat arrow notation to define the function:

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");
    })
})

Also see this answer on the cause of the problem, and other solutions: How to access the correct `this` inside a callback?



来源:https://stackoverflow.com/questions/59740303/how-to-access-this-in-cordova-plugin-with-ionic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!