【发布时间】:2020-08-29 07:40:08
【问题描述】:
我实现了无限滚动,作为其中的一部分,我触发了一个 API 端点,以根据元素位置(使用的 intersectionObserver)批量获取结果。所以在这种情况下,我会以不同的时间间隔多次访问相同的 API。有时快速滚动时,我看到调用触发得非常快,并且查看未按预期呈现。在 RXJS/Angular 中有没有办法可以合并这些响应或等待第一次调用完成才能触发第二次调用?或任何想法/建议我该如何处理?
export class {
@Output() eventscroll = new EventEmitter();
@ViewChild('iscroll')
iscroll: ElementRef<HTMLElement>;
@Component({
selector: 'myinfinitescroll',
template: `
<div #iscroll></div>
<ng-content></ng-content>
`,
});
ngAfterViewInit() {
this.zone.runOutsideAngular(() => {
this.iob.observe(this.iscroll.nativeElement);
})
}
this.iob = new IntersectionObserver(this.handleScroll(),
{ root: null, rootMargin: '0px',threshold: 0 });
handleScroll([entry]){
if (entry.isIntersecting && entry.intersectionRatio >= 0) {
this.eventscroll.emit(); ///api call happens here, currently it is just a simple HTTP post call
}
}
****Edit1****
myservicemethod(a, b, c): void {
const reqdata = {
p1 : a
p2 : b
p3 : c
};
const debounceWindow = 1000;
this._callAPI$.pipe(
concatMap((data): Observable<any> => this.myAPI.getData(reqdata)),
bufferTime(debounceWindow),
map((resp: Array<Array<any>>) => resp.reduce((acc, item) => acc = [...acc, ...item], []))
).subscribe((resp)=>{
if (resp) {
this.updateRecords();
}
})
}
我在组件构造函数上调用 this.myservice.myservicemethod,在组件 HTML 上调用 myservice._callAPI$.next($event)
【问题讨论】:
-
如果你想按顺序执行api调用,你可以使用'concatMap',同时处理滚动事件,你应该使用'fromEvent'。
标签: html angular typescript rxjs