簡體   English   中英

如何使用 RxJS 執行和獲取順序 HTTP 調用的結果

[英]How to execute and get result of sequential HTTP calls using RxJS

我想按順序進行幾次 HTTP 調用,每次調用后,我想檢查結果並進行另一個調用並顯示消息等。在某些情況下繼續下一次調用,某些情況下在顯示消息后中斷該調用。 另一方面,我還需要在每次調用中使用catchError塊(或者可能對所有調用使用一個塊,但每次調用使用一個會更好)。

因此,假設我有一個創建、更新和刪除調用,如下所示。 我怎樣才能得到這些調用的響應並檢查響應,然后執行另一個調用?

我已經嘗試過switchMapiif ,我正在尋找使用其中之一的解決方案。 有什么建議嗎?

this.service.create('/api/employee').subscribe(resp1 => {
    this.service.update('/api/salary/', id).subscribe(resp2 => {
        this.service.delete('/api/education/', id).subscribe(resp3 => {

        // I need to get response of each call from starting thr first and then continue of 
        // break according to the condition of the response

  });
});

在這里使用switchMap是一個很好的方法:

this.service.create('/api/employee')
 .pipe(switchMap((resp) => {
    if(fulfillsCondition(resp)) {
       return this.service.update(...);
    }
    return this.service.delete(...);
})).subscribe();

我不確定這里還有很多話要說。

值得注意的是, EMPTY可能是一個 RxJs 流,它不發出任何內容並立即完成。 它有點像“中斷”(以一種非常松散的方式。從流中“中斷”的方式可能非常依賴於上下文)。

this.service.create('/api/employee').pipe(
  catchError(err1 => {
    // do some stuff
    return throwError(err1);
  }),
  switchMap(resp1 => {
    // do some stuffs
    if(someCondition(resp1)){ 
      return this.service.update('/api/salary/', id).pipe(
        catchError(err2 => {
          // do some stuff
          return throwError(err2);
        }),
      );
    }
    return EMPTY;
  }),
  switchMap(resp2 => {
    // do some stuff
    if(someCondition(resp2)){ 
      return this.service.delete('/api/education/', id).pipe(
        catchError(err3 => {
          // do some stuff
          return throwError(err3);
        }),
      );
    }
    return EMPTY;
  }),
).subscribe({
  next: resp3 => { /*do some stuff*/ },
  complete: () => { /*Your stream is done*/ },
  eror: err => { /*All re-thrown errors end up here */ }
});

更新

使用tap來幫助理解流

tap是一個運算符,它返回它接收到的相同流。 它不能對您的流進行任何更改,但它可以查看在任何給定點發生的情況。 這可能是幫助您理解的有用工具。

http1().pipe(
  tap({
    next: val => console.log("Result from http1 call: ", val),
    complete: () => console.log("http1 call completed"),
    error: err => console.log("http1 call errored: ", err)
  })
  switchMap(val => http2(val).pipe(
    tap({
      next: val => console.log("Result from http2 call: ", val),
      complete: () => console.log("http2 completed"),
      error: err => console.log("http2 call errored: ", err)
    })
  )),
  tap({
    next: val => console.log("Result from switchMap operator: ", val),
    complete: () => console.log("switchMap completed"),
    error: err => console.log("switchMap (http1 or http2 call) errored: ", err)
  })
).subscribe()

在這里我們可以看到switchMap之前和之后發生的事情。 您可以看到,在這種情況下,switchMap 從 http1 獲取值並從 http2 發出值。

因為 switchMap 在生成 http2 之前等待來自 http1 的值,一個副作用是 http2 直到 http1 發出后才會啟動。 這確實意味着這些調用是按順序執行的,但是如果 http1 發出不止一次,情況就會變得更加復雜。

更多關於:

暫無
暫無

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

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