我正在学习如何编码。我正在为承诺以及如何使用它们而苦苦挣扎。
我想通过 Firebase 使用 Facebook 完成登录。
当我不将其用作服务时,代码可以完美运行
authWithFacebook(){
this.usersRef.authWithOAuthPopup("facebook", (error) => {
if (error) {
console.log(error);
}else if (this.isLoggedIn && this.newUser) {
this.usersRef.child(this.authData.uid).set({
NomComplet: this.authData.facebook.displayName,
ProfileCached: this.authData.facebook.cachedUserProfile,
Nom : this.authData.facebook.cachedUserProfile.last_name,
Prenom : this.authData.facebook.cachedUserProfile.first_name,
ProfileImg: this.authData.facebook.profileImageURL,
Agemoyen : this.authData.facebook.cachedUserProfile.age_range,
Localite : this.authData.facebook.cachedUserProfile.locale,
});
}
});
console.log("je suis connecté" + " " + this.authData.facebook.displayName )
}
我试图将我的代码转换为服务,该服务可以在整个应用程序中使用。但它不起作用:
authWithOAuth(){
return new Promise(function(resolve, reject){
this.usersRef.authWithOAuthPopup("facebook", (error) => {
if (error) {
console.log(error);
reject(error);
}else {
resolve();
}
})
})
}
任何人都可以帮助我解决这个问题或告诉我阅读哪个文档才能完全理解这一点吗?
你需要像这样重构你的代码:
authWithFacebook(){
this.authService.authWithOAuth().then(
() => {
this.usersRef.child(this.authData.uid).set({
NomComplet: this.authData.facebook.displayName,
ProfileCached: this.authData.facebook.cachedUserProfile,
Nom : this.authData.facebook.cachedUserProfile.last_name,
Prenom : this.authData.facebook.cachedUserProfile.first_name,
ProfileImg: this.authData.facebook.profileImageURL,
Agemoyen : this.authData.facebook.cachedUserProfile.age_range,
Localite : this.authData.facebook.cachedUserProfile.locale,
});
},
(err) => {
console.log(error);
}
);
}
使用承诺的then
方法。