2017-05-16 2 views
0

Ich bin ein Neuling in Angular.In Angular, wie man ein Observable mit Ergebnis und Fehlern von einem Versprechen zurückgibt

Ich entwickle einige Authentifizierungsfunktionen, die async mit einem Versprechen läuft und einige Sachen in der Mitte dieses Codes tun. In Anbetracht async glaube ich, dass die Funktion ein Observable zurückgeben sollte. Aber wie kann man ein Beobachtbares und das Ergebnis/die Fehler des Versprechens zurückgeben?

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

Ist das mit 'zufällig angularfire2'? – Jeff

+0

ja, Authentifizierung mit angularfire2 Version 4 – fhansen

Antwort

0

Ich fand einen Weg mit ReplaySubject.
(lernte von Lars Bilde Video, 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; 
    } 

und

login.component.ts 

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