Home > Mobile >  When doing server-side sorting, pagination and filtering with Angular, how can you stop multiple cal
When doing server-side sorting, pagination and filtering with Angular, how can you stop multiple cal

Time:12-10

So lets say I have a table with a datasource that gets fetched as follows

const mapperFunction = ([page, dateRange]) => this.service.getListedEvents(page, dateRange);

combineLatest([this.page$, this.dateRange$])
  .pipe(
    this.retryHelper.loadAndRetryOperator(mapperFunction, this, httpErrorConsumer)
  )
  .subscribe(listedEvents => {
    this.tableData = listedEvents;
  });

And then I have some functions linked to my html as follows

pageChange(event) {
  this.page$.next(event);
}


dateChange(event) {
  this.dateRange$.next(event);
  this.page$.next(1);
}

If I change the date, I want it to reset the page to page 1, but the unintended effect is that the API call gets kicked off twice. Firstly when the dateRange gets set, and second when the page reset happens

One possible solution would be to use a switchmap, but then its still going to fire twice, and just cancel the first one when the second emit happens, but that doesn't seem right to me.

I guess I could also use a debounce, but is that really the best solution here?

CodePudding user response:

One possible solution is to have all the parameters you want to change in a single object. It does make sense since they're all part of the request.

pageChange(event) {
  this.requestModel$.next({ 
    ...this.requestModel,
    page: event
  );
}


dateChange(event) {
  this.requestModel$.next({ 
    ...this.requestModel,
    dateRange: event,
    page: 1
  );
}

That way you can make multiple changes to the request model and it will trigger the request only once.

  • Related