2016-02-13 30 views
2

我正在學習如何編寫代碼。我正在努力承諾,以及如何使用它們。如何在angular2中使用Promise with firebase將登錄轉換爲服務

我想用Facebook和Firebase完成登錄。

的代碼工作完全當我不使用這個作爲服務

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

我attemped改造我的代碼變成一個服務,它可以在整個應用程序中使用。但它不起作用:

authWithOAuth(){ 
    return new Promise(function(resolve, reject){ 
    this.usersRef.authWithOAuthPopup("facebook", (error) => { 
     if (error) { 
     console.log(error); 
     reject(error); 
     }else { 
     resolve(); 
     } 
    }) 
    }) 
} 

任何人都可以幫助我,或告訴我哪個文件閱讀,以充分理解這一點?

回答

1

您需要重構你這樣的代碼:

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方法。

相關問題