0

I am utilizing ngx-perfect-scrollbar 5.5.12 for my Angular5 app.

When the scrollbar reach the bottom of the screen, I am going to load more data like infinite scrolling.

app.component.html

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

But the problem is that it fires the method multiple times.

app.component.ts

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

I am not sure if this is fixed in later versions but I am now utilizing v.5.5.12.

Is there a way to fix this? Or any alternative ways? Thanks.

purplefeel
  • 193
  • 2
  • 16

2 Answers2

1

I had the same issue in my project. Version: "7.1.0".

So my solution for that is to create some boolean variable for loading more items. When you are loading some data from the API set it to true - after that to false.

Example of using that in your function.

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

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

Since I don't know if you have some service for handling requests etc. I will show you some example by using BehaviorSubject.

Let say that you service is named dataService. We can create here BehaviorSubject - isLoadingData.

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

and since it's service we can create here public observable: isLoadingData = this.isLoadingDataBehaviorSubject.asObservable();`

Now when we got that all, we can create function to call API inside this service:

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({});
    })
  );
}

And you have also to subscribe to this isLoadingData inside your component and set it's value. Easiest way just for example:

ngOnInit(): {
    this.dataService.isLoadingData.subscribe(x => {
        this.isLoadingData = x;
    });
}
Mrozuu
  • 11
  • 2
0

Better solution is to verify the "scrollTop" attribute of the scrolling event is non-zero (0 means you are scrolled to the top)

.ts:

onScrollToBottom(event) {

    // fix for psYReachEnd event triggering on page load
    if(event.target.scrollTop == 0) {
        return;
    }

    ... <your code here for what to do after scrolling to the bottom>
}

HTML:

 <perfect-scrollbar (psYReachEnd)="onScrollToBottom($event)">
Collin
  • 394
  • 5
  • 14