简体   繁体   English

Angular - 避免 IntersectionObserver 的嵌套订阅

[英]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>&nbsp;</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:流动:

  1. A value from the intersection observer is fired来自交叉点观察者的值被触发
  2. Debounce operator will filter the value if the intersection observer is firing it rapidly ( Totally optional, remove this if it does not fit your use case)如果交叉点观察器快速触发它,则 Debounce 运算符将过滤该值(完全可选,如果它不适合您的用例,请删除它)
  3. Concatmap operator returns a new observable of the movies to which you can subscribe now Concatmap 运算符返回您现在可以订阅的电影的新 observable

NOTE: There is also switchMap and mergeMap the you can use that fit your use case注意:还有 switchMap 和 mergeMap 您可以使用适合您的用例

See: mergeMap参见: mergeMap

SwitchMap切换地图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM