【问题标题】:Angular5 Perfect Scrollbar psYReachEnd fires event multiple timesAngular Perfect Scrollbar psYReachEnd 多次触发事件
【发布时间】:2019-03-15 20:16:46
【问题描述】:

我正在为我的 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。

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

【问题讨论】:

    标签: angular angular5 perfect-scrollbar


    【解决方案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&lt;boolean&gt; = new BehaviorSubject(false);

    因为它是服务,我们可以在这里创建public observable: 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;
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 2016-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多