我嘗試查詢swap api中的所有人員數據。網址swapi.co/api/people會返回一個包含people數組的對象和URL(swapi.co/api/people/?page=2),我將從中獲取下一個數據。我想要做的是,每次有新頁面可用時,訂閱方法都會更新角度分量。RXJS用於分頁的循環
我是新來的反應式編程模型。我如何實現一個while循環或一系列Observable?
這適用於第一頁:
getAllPeople(): Observable<Person[]> {
let nextUrl = http://swapi.co/api;
let source = Observable.create(observer => {
this.http.get(nextUrl, { headers: this.headers })
.map(response => {
let body = response.json();
nextUrl = body.next;
return nextUrl != null ? body.results as Person[] : null;
}
)
.retry(5)//send same request based on the url of the previous request till the field next is null
.catch(error => observer.error(error))
.subscribe(persons => {
if (persons !== null) {
observer.next(persons)
}
}
);
//observer.complete();
})
return source;
}
編輯: 我添加重試()方法。我希望理解我打算做什麼更容易。在第一個請求之後,它會向同一個URL發送更多請求。不幸的是,它沒有使用我從前一個請求中獲得的新URL。
http://swapi.co/api/?page=1 - >http://swapi.co/api/?page=2 - >http://swapi.co/api/?page=3 - >空
我不知道我需要多少個請求檢索的所有數據。
你可能需要使用WebSockets,以獲取有關新頁面的通知。 –
我不熟悉websockets,但我認爲這不是我所需要的。 http獲取請求對服務器的響應告訴我在哪裏獲取下一個數據。 – qwerty
當然,如果您只需要獲取所有頁面 - 您不需要它,但是您的問題是能夠在每次有新頁面可用時更新。 –