我试图在角度2中实现滚动分页。我在div处于视口中时调用API。我试过下面的代码。这个过程中存在一个问题。当div处于视图端口时,API正在连续调用。但我希望在第一个API得到响应后第二次调用API。当div在视口中时,它正在连续调用。如何解决这个问题?
export class ListComponent implements OnInit {
getY(element: HTMLElement) {
let y = element.offsetTop;
while (element.offsetParent && element.offsetParent != document.body) {
element = <HTMLElement>element.offsetParent;
y += element.offsetTop;
}
return y;
}
getElementOnScreen(selector: string, delta: number = 1.3): any {
let windowH = self.innerHeight;
let windowY = self.pageYOffset;
let margin = windowH * delta;
return Array
.from(document.querySelectorAll(selector))
.find(el => {
let elementY = this.getY(el as HTMLElement);
let elementH = el.clientHeight;
let topOnScreen = (elementY - windowY) <= margin;
let bottomOnScreen = (windowY + margin) <= (elementY + elementH);
return topOnScreen && bottomOnScreen;
});
}
onScreen$(selector: string): Observable<boolean> {
if(this.getElementOnScreen(selector)){
let elements='';
this.inview(elements);
return Observable.fromEvent(window, 'scroll').distinctUntilChanged();
}
}
inview(eventtest) {
calling api;
}
}
列表component.html
<div id="test" [class.i-am-in-viewport]="onScreen$('div#test') |async" style="clear: both;height:200px;">
<div class="load_more" >
<p>Loading more results...</p>
</div>
</div>