首页 > 解决方案 > 组合 combineLatest 和 switchMap 时未定义

问题描述

我正在尝试将两个 Observable 组合起来,以便为接受两个值的服务调用方法提供很少的值。但在这里我有几个错误

  1. 定义 Observables 和 Subjects。

     private openSortQuerySubject: BehaviorSubject<string> = new BehaviorSubject<string>(this.formatSortQuery(this.multiSortMeta));
     public openSortQuery: Observable<string> = this.openSortQuerySubject.asObservable();
    
     private closedSortQuerySubject: BehaviorSubject<string> = new BehaviorSubject<string>(this.formatSortQuery(this.multiSortMeta));
     public closedSortQuery = this.closedSortQuerySubject.asObservable();
    
  2. 结合可观察的。

       const openQueries$ = combineLatest([this.openFilterQuery, this.openSortQuery]);
       const closedQueries$ = combineLatest([this.closedFilterQuery, this.closedSortQuery]);
    
  3. 在服务方法中使用合并值。

openQueries$
      .pipe(
        switchMap(([filter, sort]) => {
          this.alertService
            .listAlerts(filter, sort);
        }),
        tap(v => console.log(v))
      )
      .subscribe((openAlerts) => {
        this.openAlertsCount = openAlerts.length;
        this.openAlerts = this.parseAlerts(openAlerts);
      });

    closedQueries$
      .pipe(
        switchMap(([filter, sort]) => {
          this.alertService
            .listAlerts(filter, sort);
        })
      )
      .subscribe((closedAlerts) => {
        this.closedAlertsCount = closedAlerts.length;
        this.closedAlerts = this.parseAlerts(closedAlerts);
      });

标签: rxjsrxjs-observablesrxjs-pipeable-operatorsswitchmapcombinelatest

解决方案


你必须在回调中返回一个 observable(或者 RxJS 知道如何变成 observable 的东西)switchMap

不是这个:

switchMap(([filter, sort]) => {
  this.alertService.listAlerts(filter, sort);
})

但是这个(假设listAlerts返回一个可观察的,一个承诺或类似的):

switchMap(([filter, sort]) => {
  return this.alertService.listAlerts(filter, sort);
})

推荐阅读