簡體   English   中英

在Angular中將多個Http流與RxJS Observables結合

[英]Combining multiple Http streams with RxJS Observables in Angular

我試圖使以下流與map和flatMap一起工作,但是它做了它應該做的事情,但是代碼不是最佳的,例如,我第二次使用flatMap時,我從未讀取過它的響應值,但是我只是不這樣做不知道如何繼續執行流程,如果刪除流程,則會出現錯誤

類型'Observable'的參數不能分配給類型'(outerValue:any,innerValue:void,externalIndex:number,innerIndex:number)=> any'的參數

那么我該如何做得更好呢?

  person;
  facility;
  apiUrl1: string = 'http://localhost:3000/person/?';
  apiUrl2: string = 'http://localhost:3000/facility/?';
  apiUrl3: string = 'http://localhost:3000/exposure/?';

  constructor(private http: HttpClient) { }

  getData(arg): Observable<any> {
    return this.http.get(this.apiUrl1 + arg.data)
      .map((response: any) =>
        this.person = response
      )
      .flatMap((response: any) => this.http.get(this.apiUrl2 + response.val1)
        .map((response: any) => {
          this.facility = response
        })
        .flatMap((response: any) => this.http.get(this.apiUrl3 + this.person.val2)
          .map((response: any) => response.val5 * this.facility.val3)))
  }
}

如果您打算使用變量this.personthis.facilitythis.exposure只是為了“保留”這些值,以便您可以重用先前的http調用的結果,則無需這樣做。 借助.forkJoin數組解構 ,您可以消除它們。

這是一個更簡短,簡潔易讀的代碼:

getData(arg): Observable<any> {
    return this.http.get(this.apiUrl1 + arg.data)
        .flatMap((person: any) => Observable.forkJoin([...this.http.get(this.apiUrl2 + person.val1), this.http.get(this.apiUrl3 + person.val2)]))
        .map(([facility, exposure]) => exposure.val5 * facility.val3)
}

P / S:給變量取適當的名稱(而不是僅僅將它們命名為response )有助於噸

暫無
暫無

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

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