简体   繁体   English

RxJs相当于诺言链

[英]RxJs equivalent of promise chain

When chaining API calls with promises I do this: 当链接带有诺言的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)
})

How do you chain API calls like this using Observables, when the 2nd response needs data from the 1st response before it can be made? 当第二个响应需要第一个响应中的数据才能进行创建时,如何使用Observables这样链接API调用?

TIA TIA

You should use flatMap Please visit this url https://stackblitz.com/edit/angular-6-rxjx-stuff . 您应该使用flatMap请访问此URL https://stackblitz.com/edit/angular-6-rxjx-stuff I have created this project for testing RxJS. 我已经创建了这个项目来测试RxJS。

You can see the below function. 您可以看到以下功能。

  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 is an option: 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'));

Demo here: https://stackblitz.com/edit/angular-xwsltm 演示在这里: https : //stackblitz.com/edit/angular-xwsltm

Use switchMap to execute another http.get after the first pushes data. 在第一个推送数据之后,使用switchMap执行另一个http.get。 switchMap has the advantage that it cancels all pending inner requests when the parent pushes new data. 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
});

Don't forget to subscribe, since otherwise it is a cold observable. 别忘了订阅,因为否则就很冷了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM