我正在尝试使用上一次调用中的值对Reddit的API进行递归http调用。问题是前一个呼叫在下一个呼叫开始之前没有完成,因此正在进行重复呼叫。应该为每个调用更新“after”值,直到“after”值未定义。我找到了这个related post,并试图使用所描述的解决方案,但我无法弄清楚如何在下一次调用之前确保先前的调用已完成。以下是我的实际代码:
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);
});
答案 0 :(得分:6)
返回相同的函数getSavedPostsForAuthenticatedUser
将导致递归扩展。要解决此问题,您需要分离http observable。
private getSavedPostsForAuthenticatedUser(username: string, after: string, userPosts: any) {
const request$ = this._getRequest(username, after, userPosts);
if (!userPosts) {
userPosts = [];
}
return request$
.expand(response => {
if (response.data) {
for (const post of response.data.children) {
userPosts.push(post);
}
if (response.data.after) {
return this._getRequest(username, response.data.after, userPosts);
}
}
return Observable.of(userPosts);
});
}
private _getRequest(username: string, after: string) {
const headers = new Headers();
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());
}
要停止展开,您可以使用Observable.empty()
。请参阅此post。