[英]Angular - Avoid nested subscription of IntersectionObserver
I'm currently working on an infinite scroll data list where the data is loaded incrementally each time the host element is visible (invisible div at the end of each set of data).我目前正在研究一个无限滚动数据列表,其中每次主机元素可见时都会增量加载数据(每组数据末尾的不可见 div)。
I am however having trouble managing the subscriptions.但是,我在管理订阅时遇到了麻烦。 I want to make the request and push more data into the array when the element is intersected.
我想在元素相交时发出请求并将更多数据推送到数组中。
I know nested subscriptions are an anti-pattern, so how can I get around this?我知道嵌套订阅是一种反模式,那么我该如何解决呢?
Here is the template and the logic:这是模板和逻辑:
<tbody>
<tr *ngFor='let movie of movieList; trackBy:trackByMovieId' (click)="selectMovie(movie.id)">
...
</tr>
<div *ngIf="!isOneFilterActive()" #sentinel> </div>
</tbody>
...
...
...
ngAfterViewInit(): void {
this.intersectionObserver.createAndObserve(this.sentinel).pipe(
filter((isVisible: boolean) => isVisible)).subscribe(() => {
// end of list detected: request more data
this.apiManager.fetchMovies().subscribe(movieList => {
if (movieList) {
this.movieList.push(...movieList.content);
}
});
}
);
}
You can simply use a pipe operator to simplify the code like this您可以简单地使用 pipe 运算符来简化这样的代码
this.intersectionObserver.createAndObserve(this.sentinel)
.pipe(
filter((isVisible: boolean) => isVisible),
debounce(1000),
concatMap(x => this.apiManager.fetchMovies())
).subscribe(movieList => {
if (movieList) {
this.movieList.push(...movieList.content);
}
}
);
FLOW:流动:
NOTE: There is also switchMap and mergeMap the you can use that fit your use case注意:还有 switchMap 和 mergeMap 您可以使用适合您的用例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.