0

我正在为我的 Angular5 应用程序使用 ngx-perfect-scrollbar 5.5.12。

当滚动条到达屏幕底部时,我将加载更多数据,例如无限滚动。

app.component.html

<perfect-scrollbar
    [config]="config"
    (psYReachEnd)="onReachEnd()">

但问题是它会多次触发该方法。

app.component.ts

  onReachEnd() {
    console.log('log several times here');
  }

我不确定这是否在以后的版本中得到修复,但我现在正在使用 v.5.5.12。

有没有办法来解决这个问题?或者有什么替代方法?谢谢。

4

1 回答 1

1

我在我的项目中遇到了同样的问题。版本:“7.1.0”。

所以我的解决方案是创建一些布尔变量来加载更多项目。当您从 API 加载一些数据时,将其设置为 true - 然后设置为 false。

在你的函数中使用它的例子。

onReachEnd(): void {
  if (this.isLoadingData) {
    return;
  }

  // Call the API/function for more items here
}

因为我不知道您是否有一些服务来处理请求等。我将通过使用 BehaviorSubject 向您展示一些示例。

假设您的服务名为dataService。我们可以在这里创建BehaviorSubject- isLoadingData。

private isLoadingDataBehaviorSubject BehaviorSubject<boolean> = new BehaviorSubject(false);

因为它是服务,我们可以在这里创建publicobservable: isLoadingData= this.isLoadingDataBehaviorSubject.asObservable();`

现在,当我们得到所有这些后,我们可以创建函数来调用该服务中的 API:

loadData(): Observable<any> {
  this.isLoadingDataBehaviorSubject.next(true);
  return this.http.get(url).pipe(
    tap((response) => {
        this.isLoadingDataBehaviorSubject.next(false);
        return response;
    }),
    catchError((error: HttpErrorResponse) => {
        this.isLoadingDataBehaviorSubject.next(false);
        return of({});
    })
  );
}

你还必须在你的组件中订阅这个 isLoadingData 并设置它的值。最简单的方法,例如:

ngOnInit(): {
    this.dataService.isLoadingData.subscribe(x => {
        this.isLoadingData = x;
    });
}
于 2019-03-15T11:57:12.297 回答