【问题标题】:using concatMap to sequence multiple observables使用 concatMap 对多个 observables 进行排序
【发布时间】:2020-10-06 12:02:12
【问题描述】:

我正在尝试使用 RxJS concatMap 对我的 2 个 observables 进行排序,以便在调用服务返回要绑定到 Angular 9 中的 Mat-Table 的对象之前返回 employeeID。但我不确定如何编写语法正确。第一个 observable 实际上是我创建的一个行为主体,用于让组件订阅应用程序中的任何位置。第二个是来自 web api 的 http 响应。

我一直在查看此处的示例并试图弄清楚但只是敲击键盘。 RxJS concatMap

//first observable (actually a Behavior Subject)
this.userService.currentEmployeeId.subscribe(empId => this.employeeID = empId)

//second observable
this.service.getMissingContractsSummary(this.employeeID)
.subscribe(
  response => {        
    this.dataSource = new MatTableDataSource<Contractsummary>(response);
    this.dataSource.paginator = this.paginator;
  }
);

【问题讨论】:

    标签: angular rxjs angular2-observables


    【解决方案1】:

    试试下面的方法:

    import { concatMap } from 'rxjs/operators';
    
    this.userService.currentEmployeeId.pipe(
       concatMap(empId => this.service.getMissingContractsSummary(empId)),
    ).subscribe(response => {
      this.dataSource = new MatTableDataSource<Contractsummary>(response);
      this.dataSource.paginator = this.paginator;
    });
    

    concatMapswitchMapmergeMap 之间存在差异。在您的示例中,我想我会将concatMap 切换为switchMap,尽管对于您的示例来说,使用这三个中的任何一个都可以解决问题。

    https://blog.angular-university.io/rxjs-higher-order-mapping/

    【讨论】:

      【解决方案2】:

      concatMap 应该可以工作,但根据您想要的行为,您可能需要尝试switchMap。在任何一种情况下,语法都是相似的。您需要将该操作通过管道传递给currentEmployeeId observable。当它发出一个新值时,switchMap 函数可以将该值传递给您的服务的 get 函数以返回该 observable。然后,您可以按照示例代码中已有的方式进行订阅。

      this.userService.currentEmployeeId.pipe(
        switchMap(empId => this.service.getMissingContractsSummary(empId))
      ).subscribe(response => {
          this.dataSource = new MatTableDataSource<Contractsummary>(response);
          this.dataSource.paginator = this.paginator;
      })
      

      附:不要忘记取消订阅,因为看起来currentEmployeeId 可能未完成。

      【讨论】:

        猜你喜欢
        • 2010-09-26
        • 2017-05-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-23
        • 1970-01-01
        相关资源
        最近更新 更多