簡體   English   中英

如何在 angular 中使用 observable 進行一致的 http 調用?

[英]How to make consistent http calls with observable in angular?

我需要對 api 進行鏈式 http 調用。 在第一個響應中,我得到 observable,然后我使用 map 運算符並返回此結果:

     getAreaByKey(key: string): Observable<Area> {
       return this.http.get<any[]>(`${this.api}/areas/${key}`).pipe(
        map(result => {
          return {
             'key': result['Key'],
             'name': result['Description'],
             'experts': result['Experts']
          };
       })
     );
  }

然后我需要使用參數result['Experts']進行另一個 http 調用,它是帶有 ID 的數組。 如何將該參數傳遞給下一次調用? 我嘗試使用 SwitchMap,但沒有結果。 以及如何保存此調用的響應數據? 因為我需要在我的模板中同時使用兩者。

switchMap是用於鏈接 http 調用的正確運算符。 每當第一個 observable 發出時,您就可以使用發出的值創建第二個 observable。

在你的例子中:

getAreaByKey(key: string): Observable<Area> {
   return this.http.get<any[]>(`${this.api}/areas/${key}`).pipe(
      map(result => {
         return {
            'key': result['Key'],
            'name': result['Description'],
            'experts': result['Experts']
         };
      }),
      tap(res1 => // save the first response here),
      switchMap(res1 => this.anotherHttpCall(res.experts)),
      tap(res2 => // save the second response here)
   );
}

至於保存數據,您可以在每個 observable 之后點擊執行此操作,或者您可以使用async | pipe 模板中的async | pipe

如果沒有結果,則可能是您沒有訂閱 observable:

const obs$ = this.getAreaByKey();  // the observable is defined but the http call has not been made
obs$.subscribe();  // http call is triggered

同樣,您可以像上面那樣手動執行此操作或使用async | pipe 模板中的async | pipe

查看https://angular.io/guide/observables

myObservable.subscribe(
   x => console.log('Observer got a next value: ' + x),
   err => console.error('Observer got an error: ' + err),
  () => console.log('Observer got a complete notification')
);

暫無
暫無

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

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