【问题标题】:Avoiding nesting subscriptions in Angular 2+?避免在 Angular 2+ 中嵌套订阅?
【发布时间】:2020-09-01 10:30:50
【问题描述】:

我有 2 个端点:

  • 1 个端点可让当前用户登录。
  • 1 个端点获取此用户的授权。

其实我用的是:

this.user
  .subscribe((e) => {
     this.grants.get(e)
        .subscribe((x) => {
            console.log(x)
         })
  })

但这是 Angular 2+/RxJS 的反模式。

我想知道如何按照 Angular/RxJS 最佳实践来做到这一点。

谢谢

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    避免嵌套订阅取决于可观察对象的性质以及它们如何相互依赖:

    共同依赖的 observables

    当一个 observable (this.grants.get()) 依赖于来自另一个 observable (this.user) 的通知时,您可以使用任何 RxJS 高阶映射运算符 switchMap、mergeMap、concatMap 和 exhaustMap .每个人都有自己的目的。你可以找到它们之间的区别here。

    b/n 的简要区别

    • switchMap - 如果外部 observable 发出,则取消内部 observable
    • mergeMap - 为每个外部通知触发内部 observable(展平外部通知)
    • concatMap - 本质上是 mergeMap,随时都有单个并发请求(扁平化外部通知,但按顺序发出)
    • exhaustMap - 如果内部 observable 尚未完成,则忽略外部通知

    使用switchMap 运算符的说明

    this.user.pipe(
      switchMap(e => this.grants.get(e))
    ).subscribe((x) => {
      console.log(x)
    });
    

    独立的可观察对象

    如果 observables 彼此独立,您可以使用 RxJS 函数,如 forkJoin、combineLatest 或 zip 来并行触发 observables。

    b/n 的简要区别

    • forkJoinα - 仅在所有可观察对象完成时发出
    • combineLatestα,β - 当任何可观察对象发射时发射(不发射的可观察对象将发射旧值)
    • zipα,β - 当 所有 的 observables 发射时发射

    使用forkJoin的插图

    forkJoin(this.obs1, this.obs2, ...).subscribe(
      res => console.log(res)
    );
    

    α - 从每个 observable 发出一组通知(例如,(this.obs1, this.obs2, ...) 将发出 ['res from obs1', 'res from obs2', ...])。

    β - 所有可观察对象应该至少发射一次以供操作员发射

    【讨论】:

      【解决方案2】:

      在您的代码中,它们看起来彼此没有依赖关系,因为this.user 的结果未在this.grants.get 中使用,但我现在将忽略它。

      您可以使用await 关键字来防止嵌套。

      例如,您可以执行以下操作:

      const user  = await this.user.toPromise();
      const grants = await this.grants.get().toPromise();
      

      【讨论】:

      • this.grants.get 确实使用来自this.user 的返回值。另外,没有必要从 Observable 范式切换到 Promise 范式,而且,如果user 多次发出,它会破坏事情。
      • 这里有多个问题:(1).从 observables 到 promise 的不必要切换。 (2)。 OP 的 observables 是相互依赖的。 (3)。 toPromise() 方法在 RxJS 7 中是 being deprecated,将在 RxJS 8 中消失。
      【解决方案3】:

      谢谢你们。它与 switchMap 一起使用。

      import { Component, VERSION, OnInit } from '@angular/core';
      import { HttpClient } from '@angular/common/http';
      import { switchMap } from 'rxjs/operators';
      
      @Component({
        selector: 'my-app',
        templateUrl: './app.component.html',
        styleUrls: [ './app.component.css' ]
      })
      export class AppComponent implements OnInit {
        name = 'Angular ' + VERSION.major ;
      
        constructor(private http: HttpClient) {
        }
      
        ngOnInit() {
          this.http.get("https://pokeapi.co/api/v2/pokemon?limit=100&offset=200")
            .pipe(
              switchMap((mp) => {
                console.log("Requisição 01", mp);
                return this.http.get("https://pokeapi.co/api/v2");
              }),
              switchMap((it) => {
                console.log("Requisição 02", it);
                return this.http.get("https://pokeapi.co/api/v2/pokemon/206/");
              })
            )
            .subscribe((d) => console.log("subscribe", d))
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2022-08-25
        • 2023-01-30
        • 2020-11-30
        • 2020-05-31
        • 2018-11-27
        • 2023-01-11
        • 2020-08-18
        • 2019-10-03
        • 1970-01-01
        相关资源
        最近更新 更多