如何在 angular 中递归执行 HTTP 请求?

How to recursively perform an HTTP request in angular?

我需要向包含帖子列表和总帖子键的端点发出获取请求。

{
    posts: [{}, {}, {}, ...],
    total: 1000
}

请求的偏移量 key 决定了帖子的数量 return。

// request
https://postBalzer.com/posts?offset=0&limit=50

此请求 return 个帖子从 0 - 50 如何使调用递归,直到使用 Angular HttpClientModule.

获取所有帖子

在这种情况下如何使用 expand rxjs 运算符?

getData() {
    if (this.total < 50) {
        this.service().subscribe((response) => {
            this.total += response.length;
            this.getData()
        })
    }
}

这可以在 rxjs 中使用 expand 运算符完成,如下所示:

import {HttpParams} from '@angular/common/http';
import {Observable, empty} from 'rxjs';
import {expand, map, reduce} from 'rxjs/operators';

export interface PostResponse {
  posts: object[];
  total: number;
}

@Injectable()
export class Service {
  private readonly baseUrl = '...';

  constructor(private http: HttpClient) {
  }

  getPosts(chunkSize: number): Observable<object[]>
  {
    let chunkOffset = 0;
    return this.getPostsChunk({chunkOffset++, chunkSize}).pipe(
      expand(({total}) => total >= chunkOffset * chunkSize
                                ? getPostsChunk({chunkOffset++, chunkSize})
                                : empty()
      ),
      map(res => res.posts),
      // if you want the observable to emit 1 value everytime that
      // a chunk is fetched, use `scan` instead of `reduce`
      reduce((acc, val) => acc.concat(val), new Array<object>()),
    );
  }

  getPostsChunk({chunkOffset, chunkSize}: {chunkOffset?:number, chunkSize:number})
  {
     const offset = (chunkOffset || 0) * chunkSize;
     const limit = offset + chunkSize;
     const params = new HttpParams({offset, limit});
     return this.http.get<PostResponse>(this.baseUrl, {params});
  }
}

考虑到您可以 "calculate" 从第一次请求后获得的 总数 值中获取所有 post 条目所需的请求数,您绝对可以在不使用 expand 运算符的情况下以不同的方式实现这一点。