簡體   English   中英

RxJS Observable返回數組,每次迭代運行另一個函數

[英]RxJS Observable returning array, run another function with each array iteration

我有一個函數getNews() ,它基本上返回angular的http.get請求。 請求的結果是Id的數組。 我想迭代我得到的這個數組並運行另一個http.get請求(函數getItem(id) ),然后返回從服務器接收的單個Id的對象。

我試過這樣使用它:

  getLatest() {
    return this.http.get('all_news_url')
    .map(res => res.json())
    // I even tried creating Observable from array and get only 5 elements
    //.map(res => Observable.from(res.json()))
    //.take(5)
    .map((data) => this.getItem(data))
    .subscribe(
      data => {
        console.log(data);
      }
    )
  }

  getItem(itemId: any): Observable<any> {
    console.log('item id', itemId);

    return this.http.get(this.generateUrl(`item/${itemId}`))
    .map(res => res.json());
  }

顯然,這不起作用。 getItem()函數的參數總是作為Id的整個數組傳遞。

感謝大家參與這個問題。

您可能希望使用concatMap運算符而不是map。 concatMap將返回的Observable展平為源Observable,而map返回一個observable的observable。

如果您希望getItem()中的數據與'all_news_url'中列出的順序相同,您可以嘗試類似

this.http.get('all_news_url')
.concatMap(res => Observable.from(res.json()).take(5))
.concatMap((data) => this.getItem(data))
.subscribe(
  data => {
    console.log(data);
  }
);

使用上面的代碼,對getItem()的調用將是同步的,即一次只有一個請求'item / $ {itemId}',並按順序

如果您不關心訂單並想通過一次發送多個請求來加速它們,請將第二個concatMap更改為mergeMap。 請注意,請求(對於item / itemId)仍然是有序的,但不能保證響應的順序。 您可以提供最大並發請求作為mergeMap的第三個參數(通過傳遞undefined或null忽略第二個參數)。

.concatMap(res => Observable.from(res.json()).take(5))
.mergeMap((data) => this.getItem(data), null, 3)

傳遞1作為mergeMap的第三個參數將等同於concatMap

暫無
暫無

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

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