2017-10-16 42 views
0

我有一個關於觀察到的問題。 例如,我們的API,併發送reguest有:可觀察 - 使動態請求的隊列(角4)

this.http.get('https://swapi.co/api/people/').subscribe(peoplesData => { 
    let peoples = peoplesData.json(); 
    let nextPage = peoples.next; // https://swapi.co/api/people/?page=2 
    this.peoples = peoples.results; 
}); 

當我第一次發送的請求,我將獲得下一個請求的URL(在這個例子中,URL中包含「下一頁」)。 我需要創建方法,這將使所有請求,以後每請求將全部添加「結果」到「this.peoples」。 我認爲,.mergeMap和switchMap不適合它。 也許是你有更多的expirience與可觀察?請用這種方法幫助我。

更新 我解決了這個問題.expand:

return this.http.get('https://swapi.co/api/people/') 
     .expand(peoplesData => { 
     let peoples = peoplesData.json(); 
     if (peoples.next) { 
      return this.http.get(peoples.next); 
     } else { 
      return Observable.empty(); 
     } 
     }) 
     .map(peoples => peoples.json()); 
+0

至於我在這裏可以看到,唯一的問題在您的文章是「你對Observables的使用經驗比我多嗎?」而且,鏈接因爲過期而不好。編輯你的帖子以包含鏈接的代碼,PLZ。 –

+1

@TheHeadRush,謝謝你。我編輯了我的帖子並添加了示例。你能幫我選擇一種合適的可觀察方法嗎? –

+0

看看這個:https://stackoverflow.com/questions/38712121/angular2-nested-http-requests –

回答

0

使用rxjs的Rx flatMap我的解決辦法:

import {Observable} from 'rxjs/Rx'; 


ngOnInit() { 
    const arrayIds = [2456, 12456, 456, 7899]; 
    this.doUsersRequest(arrayIds); 
} 

doUsersRequest(queryArr, previousObservable = null) { 
     if (queryArr.length) { 
      const url = 'api/users/id/' + queryArr.shift(); 
      let observable = null; 
      if (previousObservable) { 
       observable = previousObservable.flatMap(() => { 
        return this.http.get(url); 
       }); 
      } else { 
       observable = this.http.get(url); 
      } 
      return this.doUsersRequest(queryArr, observable); 
     } else { 
      return previousObservable; 
     } 
    }