首页 > 解决方案 > RxJs 相当于 Promise 链

问题描述

当使用 Promise 链接 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)
})

当第二个响应需要来自第一个响应的数据才能进行时,您如何使用 Observables 链接这样的 API 调用?

TIA

标签: angularrxjs

解决方案


您应该使用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); });
  }

推荐阅读