我正在嘗試使用前一個調用的值對Reddit的API進行遞歸http調用。問題在於之前的呼叫在下一個呼叫開始之前沒有完成,因此正在進行重複呼叫。應該爲每次調用更新「after」值,直到「after」值未定義爲止。我發現這個related post,並試圖使用所描述的解決方案,但我無法弄清楚如何在下次調用之前確保先前的調用已完成。下面是我的實際代碼:角 - 正確使用RXJS展開運算符進行遞歸http調用
private getSavedPostsForAuthenticatedUser(username: string, after: string, userPosts: any) {
const headers = new Headers();
if (!userPosts) {
userPosts = [];
}
headers.append('Authorization', `Bearer ${this._token}`);
const redditUrl = `${RetainerConfig.redditOauthUrl}user/${username}/saved`;
const url = after ? `${redditUrl}/?after=${after}` : redditUrl;
return this._http.get(url, { headers: headers })
.map(response => response.json())
.expand(response => {
if (response.data) {
for (const post of response.data.children) {
userPosts.push(post);
}
if (response.data.after) {
return this.getSavedPostsForAuthenticatedUser(username, response.data.after, userPosts);
}
}
return Observable.of(userPosts);
});
問題的一部分可能是您傳遞給'expand'的項目函數永遠不會返回空的可觀察項。如果不這樣做,我看不出擴張會如何停止。 – cartant
這是正確的。正如在接受的答案中指出的那樣,我還遞歸地調用了引發類似問題的擴展運算符。 – jacobisaman