关于如何使用SCAN实现显示更多功能的请求(Angular RxJS Streams HTTP request - show more items)。我怎么能合并响应(扫描)只有当偏移量已更新,而不是当搜索paramMap更新?
返回数据的My Service
public getProductsV3(paramMap: Observable<ParamMap>):Observable<ProductResponseApi>{
const combineLatest$ = combineLatest([this.offset$,this.limit$,paramMap]).pipe(
switchMap(([offset,limit,paramMap])=>this.fetchProductsFromApiV2(offset,limit,paramMap.get('q') as string))
)
return combineLatest$.pipe(
scan((prev, current) => {
return {
infos: current.infos,
products: [...prev.products, ...current.products]
};
})
);
}
它可以工作,但是当我使用ParamMap查找另一个产品时,由于扫描,它与之前的结果相结合。如何在偏移量发生变化时才进行扫描?
尝试withLatestFrom
const combineLatest$ = combineLatest([this.offset$,this.limit$]).pipe(
withLatestFrom(paramMap),
switchMap(([[offset,limit],paramMap])=>this.fetchProductsFromApiV2(offset,limit,paramMap.get('q') as string))
)
或take
const combineLatest$ = combineLatest([this.offset$,this.limit$,paramMap.pipe(take(1))]).pipe(
switchMap(([offset,limit,paramMap])=>this.fetchProductsFromApiV2(offset,limit,paramMap.get('q') as string))
)
我从我的问题中找到了答案。感谢这个视频https://www.youtube.com/watch?v=aKsPMTP6-sY&t=970s&ab_channel=JoshuaMorony
return combineLatest([paramMap]).pipe(
switchMap(([search])=> {
const productForCurrentPage$ = this.offset$.pipe(
concatMap((offset) =>
this.http.get<ProductResponseApi>(this.apiUrl+`/search?q=${search.get('q')}&offset=${offset}`)
)
)
const allProducts$ = productForCurrentPage$.pipe(
scan((prev, current) => {
return {
infos: current.infos,
products: [...prev.products, ...current.products]
};
})
)
return allProducts$;
})
)