首页 > 解决方案 > Angular 使用带有 BehaviorSubject 和 ExhaustMap 的 NgBusy

问题描述

ng-busy与更复杂的 RxJS 运算符(如switchMapexhaustMap在 a 上)一起使用时,最佳实践是什么BehaviorSubject

如果你设置 this.busy ,BehaviorSubject它总是很忙,因为它关闭了BehaviorSubject不是 Http 请求订阅。

public currentPage$ = new BehaviorSubject(1);

// ...

// Not sure how to use "busy" this way:
this.currentPage$
  .pipe(
    exhaustMap((page: number = 1) =>
      (page) ? this.getAlerts(page) : empty()
    ),
    map((response: HttpResponse<Alert[]>) => 
      response.results
    )
  )
  .subscribe(
    (alerts: Alert[]) => { ... },
    (error: any) => { ... }
  );

正如我从这样的文章中了解到,以下代码在使用 observables 时不是最佳实践,但我不知道该怎么做。

但这就像 Observableception,对吧?不,Observables 不喜欢在 Observables 中。

this.currentPage$
  .subscribe(
    (page: number = 1) => {

     // Can use "busy" this way:
     this.busy = this.getAlerts(page)
        .pipe(
          map((response: HttpResponse<Alert[]>) => 
            response.results
          )
        )
        .subscribe(
          (alerts: Alert[]) => { ... },
          (error: any) => { ... }
        );
    },
    (error: any) => { ... }
  );

标签: angular

解决方案


如果您希望在管道流中触发副作用,则tap操作符是 goto:

this.currentPage$.pipe(
  exhaustMap((page: number = 1) => { 
    if(page) {
      const obs$ = this.getAlerts(page).pipe(share());
      this.busy = obs$.subscribe();
      return obs$;
    } else
      return empty();
  }),
  map((response: HttpResponse<Alert[]>) => response.results),
).subscribe(
  (alerts: Alert[]) => { ... },
  (error: any) => { ... }
);

推荐阅读