2017-05-16 66 views
0

我是Angular的新手。在Angular中,如何從promise中返回帶有結果和錯誤的Observable

我正在開發一些身份驗證函數,它使用promise來運行異步,並在此代碼中執行一些操作。 考慮到異步,我相信函數應該返回一個Observable。但是,如何返回Observable以及承諾的結果/錯誤?

authentication.service.ts 

    loginwithProvider(): <????> { 
     this.auth.signInWithPopup(provider) 
      .then(result =>{ 
          /* do some things, such as getting data and logging */ 

          }) 
      .catch((error) => { 
          /* receive the error of the provider, do some things, such as logging */ 
          }) 

     return ????? <---- I want to return result and errors of the provider in an Observable to the caller function 
    } 


login.component.ts 

onLogin(){ 

    this.request = this.authenticationService.loginWithProvider().subscribe(
    (data) => { 
     console.log("onlogin - then success"); 
     this.router.navigate(['/']); 
    }, 
    (error) => { 
      console.log(" onlogin - error ", error); 
      show_error_to_user(error); <---- error from loginWithProvider 
    }); 

} 
+0

這是由偶然'angularfire2'? – Jeff

+0

是的,使用angularfire2版本4進行身份驗證 – fhansen

回答

0

我找到了一種使用ReplaySubject的方法。
(從拉斯Bilde視頻瞭解到,https://www.youtube.com/watch?v=mdD2sy7r7Mk

authentication.services.ts 
loginWithProvider() : ReplaySubject<any> { 
    let resultSubject = new ReplaySubject(1); 
    var provider = new firebase.auth.FacebookAuthProvider(); 

    this.afAuth.auth.signInWithPopup(provider) 
     .then(result => { 
     /* do some things, such as getting data and logging */ 
     console.log("result", result) 
     resultSubject.next(result); 
     // return result; 
     }).catch((error) => { 
     /* receive the error of the provider, do some things, such as logging */ 
     console.log("error", error) 
     resultSubject.error(error); 

    }) 
    return resultSubject; 
    } 

login.component.ts 

onlogin() { 
     this.authenticationService.loginWithProvider() 
     .subscribe(
     (data) => { 
     console.log("onloginwithprovider - then success", data); 
     this.router.navigate(['/']); 
     }, 
     (error) => { 
      console.log(" onloginwithprovider - error ", error) 
     }); 
    } 
相關問題