代码之家  ›  专栏  ›  技术社区  ›  danday74

承诺链的RxJs等价物

  •  0
  • danday74  · 技术社区  · 6 年前

    当用承诺链接API调用时,我会这样做:

    this.http.get('/api/hello').toPromise().then(res => {
      return this.http.get('/api/there/' + res.id).toPromise()
    }).then(res => {
      console.log('res from 2nd call', res)
    }).catch(err => {
      console.log('err', err)
    })
    

    当第二个响应需要来自第一个响应的数据时,如何使用observates来链接这样的API调用?

    短暂性脑缺血发作

    3 回复  |  直到 6 年前
        1
  •  3
  •   Vivek Kumar    6 年前

    你应该使用 flatMap https://stackblitz.com/edit/angular-6-rxjx-stuff . 我创建了这个项目来测试RxJS。

    您可以看到下面的函数。

      test__flatMap() {
        const post$ = this.getPosts();
        const users$ = this.getUsers();
        const users2$ = this.getUsers();
    
        post$.pipe(
          flatMap(data => {
            console.log('data 1 >>> ', data);
            return users$;
          }),
          flatMap(data => {
            console.log('data 2 >>> ', data);
            return post$;
          }),
        ).subscribe(data => { console.log(`In the end >>> `, data); });
      }
    
        2
  •  1
  •   Felix Lemke    6 年前

    使用 switchMap 在第一次推送数据之后执行另一个http.get。 它的优点是在父级推送新数据时取消所有挂起的内部请求。

    const request$ = this.http.get('pathto/api').pipe(
      switchMap((res) => {
        return this.http.get(`another/api/${res.id}`)
      })
    );
    
    request$.subscribe(innerRequestData => {
      // do whatever you want
    });
    

    别忘了订阅,否则这是一个很好的选择 寒冷的 可观察的。

        3
  •  1
  •   User3250    6 年前

    mergeMap

    this.http.get(/api/hello')
        .pipe(mergeMap((s) => {
            return s;
        }),
        mergeMap((res) =>{
          const url ='/api/there/' + res.id;
          return this.http.get(url).pipe(map((res) =>   {
                return res;
            }));
        }))
        .subscribe(res => {
            console.log(res);//final response
        }, 
        undefined,
        () => console.log('complete'));
    

    此处演示: https://stackblitz.com/edit/angular-xwsltm