简体   繁体   English

用于 Firebase 身份验证 RxJs 的嵌套排气映射和连接映射

[英]Nested exhaustMap and concatMap for Firebase Authentication RxJs

I'm trying to implement Firebase Authentication and sending received user's data to the server for creating account in my app.我正在尝试实现 Firebase 身份验证并将接收到的用户数据发送到服务器以在我的应用程序中创建帐户。

Here is the code:这是代码:

  ngAfterViewInit(): void {
    const provider = new firebase.auth.GoogleAuthProvider();
    fromEvent(this.LoginWithGoogle.nativeElement, 'click')
      .pipe(
         exhaustMap(() =>
           from(this.afAuth.signInWithPopup(provider)).pipe(
              map((data) => data.user),
              concatMap((user) =>
                this.authService.loginWithGoogle({
                   email: user.email,
                   username: user.displayName,
                })
              )
           )
         )
       )
       .subscribe((res) => {
           console.log(res);
       });
  }

It works well.它运作良好。 But is it right to use nested RxJs operators like this?但是像这样使用嵌套的 RxJs 运算符是否正确? And there is any alternative solution for this case?这种情况有什么替代解决方案吗?

I think this would work:我认为这会起作用:

ngAfterViewInit(): void {
  const provider = new firebase.auth.GoogleAuthProvider();
  
  fromEvent(this.LoginWithGoogle.nativeElement, 'click')
    .pipe(
        exhaustMap(() => from(this.afAuth.signInWithPopup(provider))),
        map((data) => data.user),
        concatMap((user) => this.authService.loginWithGoogle({ 
            email: user.email,
            username: user.displayName,
          })
        )
      )
      .subscribe((res) => {
          console.log(res);
      });
}

When you're using operators like switchMap , exhaustMap , mergeMap , concatMap , which handle inner observables automatically, you can simply imagine that instead of manually subscribing to that the callback returns, you let that job do be done by the operator.当您使用诸如switchMapexhaustMapmergeMapconcatMap的自动处理内部可观察对象的运算符时,您可以简单地想象一下,与其手动订阅回调返回,不如让该工作由运算符完成。 In addition to this, the value emitted by the inner observable is passed along to the outer observable(most of the times - the main stream).除此之外,内部 observable发出的值会传递给外部 observable(大多数时候 - 主流)。 That's why I was able to use map on the save level as exhaustMap .这就是为什么我能够在保存级别上使用map作为exhaustMap

Edit编辑

If you also want to handle errors in inner observables, you can use something like this:如果你还想处理内部 observables 中的错误,你可以使用这样的东西:

exhaustMap(() => from(...).pipe(catchError(() => EMPTY)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM