Home > OS >  how to assign latest request data to table in angular
how to assign latest request data to table in angular

Time:03-01

I have 3 tabs in one page component. Once we click on tab, passing tab key to API to get filtered data based on tab key.

this.taskService.getAllTasks(this.tabKey).subscribe((data: Tasks[]) => {
  this.taskList = data;
});

When tabs are quickly switched the same API is getting called with different keys and all API calls are executing without cancellation and every response data is assigned to the tasklist variable. How do I assign the latest request data to the tasklist variable by canceling old requests?

CodePudding user response:

On tab change call a function inside that unsubscribe all api request except latest api that you want to use.

CodePudding user response:

You should set tabKey changes in an observable and use switchMap to cancel prior requests:

readonly tabKeySubject = new Subject<string>();

ngOnInit(): void {
  this.tabKeySubject.pipe(
    switchMap((tabKey) => this.taskService.getAllTasks(this.tabKey))
  ).subscribe(data => this.taskList = data);
}

If this is occurring in a component, and it doesn't have a major effect, it would be better to move the stream for task list data into an observable field and use the async pipe to display into in the template. Otherwise remember to unsubscribe to avoid memory leaks.

readonly tabKeySubject = new Subject<string>();

readonly taskList$ = this.tabKeySubject.pipe(
  switchMap((tabKey) => this.taskService.getAllTasks(this.tabKey))
);

Something else... You may want in your ui to clear the list while the new list is loaded. In that case a simple thing to do would be to use startWith with either undefined or an empty array so the list gets cleared.

this.tabKeySubject.pipe(
  switchMap((tabKey) => this.taskService.getAllTasks(this.tabKey)),
  startWith(undefined)
);
  • Related