【问题标题】:How to chain variable number of observables?如何链接可变数量的可观察对象?
【发布时间】:2021-12-30 23:56:46
【问题描述】:

我对 Angular 和 Observables 很陌生。我想链接服务调用一定次数。有没有使用 Observables 的简单方法? (有点像that,但使用了一种通用的方式)。

this.myService.getNodeById(res.parent_id).subscribe(res => {
  this.myService.getNodeById(res.parent_id).subscribe(res => {
     this.myService.getNodeById(res.parent_id).subscribe(res => {
        // while res.parents_id exists
     });
  });
});
  • 角度:12.0.5
  • 打字稿:4.2.3
  • rxjs:6.6.0

【问题讨论】:

标签: angular typescript rxjs


【解决方案1】:

你可以这样写一个递归函数:

getNodeById(id) {
  return this.myService
    .getNodeById(id)
    .pipe(switchMap((x) => (x.parent_id ? this.getNodeById(x.parent_id) : of(x))));
}

【讨论】:

    【解决方案2】:

    您可以创建一个自定义的 Rx.js 运算符,它基本上调用 switchMap 中所需的 API

    type GetNodeFn<TNode = any, TResponse = any> = (
      res: TNode
    ) => Observable<TResponse>;
    
    // custom getNode operator
    function getNode<TNode>(nodeFn: GetNodeFn) {
      return (observable: Observable<TNode>) =>
        observable.pipe(switchMap((res) => nodeFn(res)));
    }
    
    this.myService.getNodeById(res.parent_id).pipe(
      getNode((res) => this.myService.getNodeById(res.parent_id)),
      getNode((res) => this.myService.getNodeById(res.parent_id))
    );
    

    【讨论】:

      猜你喜欢
      • 2016-04-24
      • 1970-01-01
      • 2021-08-26
      • 1970-01-01
      • 2015-01-12
      • 1970-01-01
      • 2019-09-09
      • 2018-10-25
      • 2018-06-07
      相关资源
      最近更新 更多