簡體   English   中英

RxJs相當於諾言鏈

[英]RxJs equivalent of promise chain

當鏈接帶有諾言的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

您應該使用flatMap請訪問此URL 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是一個選項:

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

在第一個推送數據之后,使用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
});

別忘了訂閱,因為否則就很冷了

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM