问题描述
我需要向一个端点发出一个 get 请求,该端点包含一个帖子列表和一个帖子总数.
I need to make a get request to an endpoint which contains a list of posts and a key of total posts.
{
posts: [{}, {}, {}, ...],
total: 1000
}
请求的偏移量键决定了返回的帖子数.
the offset key for the request determines the number of posts return.
// request
https://postBalzer.com/posts?offset=0&limit=50
此请求返回 0 - 50 的帖子如何使调用递归,直到使用 Angular HttpClientModule 获取所有帖子.
this request return posts from 0 - 50How to make the call recursive until all the posts are fetched using Angular HttpClientModule.
在这种情况下如何使用 expand rxjs 运算符?
How can I use the expand rxjs operator in such a case?
推荐答案
这可以在 rxjs 中通过使用 expand
操作符来完成,如下所示:
This can be done in rxjs by using the expand
operator as follows:
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});
}
}
考虑到您可以计算"从第一个请求后获得的 total 值中获取所有帖子条目所需的请求数量,您绝对可以以不同的方式实现这一点,而无需使用expand
运算符.
Considering that you can "calculate" the number of requests required to fetch all the post entries from the total value obtained after the 1st request, you can most definitely implement this in a different way without using the expand
operator.
这篇关于如何以角度递归执行 HTTP 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!