Angular - Correctly using RXJS expand operator to make recursive http calls

后端 未结 1 1662
既然无缘
既然无缘 2020-12-17 06:36

I am attempting to make recursive http calls to Reddit\'s API using a value from the previous call. The problem is that the previous call is not finished before the next one

相关标签:
1条回答
  • 2020-12-17 07:30

    Returning the same function getSavedPostsForAuthenticatedUser will cause recursive expands. To solve this you need to separate the 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());
      }
    

    To stop the expanding you may use Observable.empty(). Please refer to this post.

    0 讨论(0)
提交回复
热议问题