【问题标题】:In Angular, how to return an Observable with result and errors from a promise在 Angular 中,如何从 Promise 中返回带有结果和错误的 Observable
【发布时间】:2017-10-15 12:19:27
【问题描述】:

我是 Angular 的新手。

我正在开发一些身份验证功能,这些功能与 Promise 异步运行,并在这段代码中间做一些事情。 考虑到异步,我相信该函数应该返回一个 Observable。但是如何返回 Observable 和 promise 的结果/错误?

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

}

【问题讨论】:

  • 这是与angularfire2 的巧合吗?
  • 是的,使用 angularfire2 版本 4 进行身份验证

标签: javascript angular promise observable


【解决方案1】:

我找到了一种使用 ReplaySubject 的方法。
(借鉴 Lars 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)
        });
    }

【讨论】:

    猜你喜欢
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多