I have a component which is using url params.
On the ActivatedRoute.params change event, Http call is being sent to the server to get some details based on the ID param from the url.
The issue is in a case as following:
Once the url was changed to have new param, a new call was sent - this is OK.
then - the url was changed again so a newer call was now sent.
BUT - sometimes the old call response is coming AFTER the new one so the data is not correct and not matching latest URL.
What I actually need is a way to cancel the call once the url was changed.
I tried a solution based on this answer I found, with my below changes to match my case, but it doesn't seem to work.
app-routing.module.ts:
{ path: 'person-details/:id', component: PersonDetailsComponent }
person-details.component.ts:
protected ngUnsubscribe: Subject<void> = new Subject<void>();
ngOnInit(){
this.activatedRouter.params
.subscribe( (params) => {
//here is what I tried to cancel prev calls
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
//the call
this.personService.getPersonDetails(params['id'])
//add call to ngUnsubscribe
.pipe( takeUntil(this.ngUnsubscribe))
.subscribe( (person) => {
//the old call response gets here after the new one so now
//this.person is not the latest one and not matching the id in the current url
this.person = person;
});
}
Note: ngOnDestroy is not being called if only the params in the url were changed, so doesn't match my case
What is the correct solution?