Ane*_*ees 1 recursion rxjs angular angular-httpclient
我需要向包含帖子列表和帖子总数的密钥的端点发出获取请求。
{
posts: [{}, {}, {}, ...],
total: 1000
}
Run Code Online (Sandbox Code Playgroud)
请求的偏移键决定返回的帖子数量。
// request
https://postBalzer.com/posts?offset=0&limit=50
Run Code Online (Sandbox Code Playgroud)
此请求返回 0 - 50 之间的帖子 如何使调用递归,直到使用 Angular HttpClientModule 获取所有帖子。
在这种情况下如何使用 Expand rxjs 运算符?
这可以在 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});
}
}
Run Code Online (Sandbox Code Playgroud)
考虑到您可以从第一个请求后获得的总值中“计算”获取所有帖子条目所需的请求数,您绝对可以在不使用expand
运算符的情况下以不同的方式实现此目的。
归档时间: |
|
查看次数: |
3930 次 |
最近记录: |