使用 concatMap 对多个可观察对象进行排序

using concatMap to sequence multiple observables

我正在尝试使用 RxJS concatMap 对我的 2 个可观察对象进行排序,以便它 return 在将服务调用到 return 绑定到我的 Mat-[=19 的对象之前使用 employeeID =] in Angular 9. 但我不确定如何正确编写语法。第一个 observable 实际上是我创建的一个行为主题,让组件可以订阅应用程序中的任何地方。第二个是来自网络 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;
  }
);

按以下方式尝试:

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,尽管对于您的示例来说,使用这 3 个中的任何一个都可以解决问题。

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

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

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

P.S。不要忘记退订,因为看起来 currentEmployeeId 可能无法完成。