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