【问题标题】:RxJs equivalent of promise chainRxJs 相当于 Promise 链
【发布时间】:2018-10-18 16:56:58
【问题描述】:

当使用 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

【问题讨论】:

  • switchMap 或 mergeMap
  • 记住mergeMapflatMap的新名字

标签: angular rxjs


【解决方案1】:

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

【讨论】:

  • 记住 mergeMap 是 flatMap 的新名称 - 谢谢@Picci
【解决方案2】:

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

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
});

不要忘记订阅,否则它是一个 cold 可观察的。

【讨论】:

    【解决方案3】:

    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

    【讨论】:

    • 记住 mergeMap 是 flatMap 的新名称 - 谢谢@Picci
    • @danday74 感谢替换为 mergeMap 并添加了 stacblitz 演示。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 2018-02-05
    • 2013-07-21
    • 2021-09-22
    • 1970-01-01
    • 2018-08-29
    相关资源
    最近更新 更多