I've noticed i'm getting multiple subscriptions when I navigate between routes in my angular app.
In my parent component I have some routes like this:
<li routerLink="route1" [routerLinkActive]="['active']">Route 1</li>
<li routerLink="route2" [routerLinkActive]="['active']">Route 2</li>
Those two routes both load the same child component which then gets some data from my service:
component.ts
this._entityService.getEntities(this.jobId, this.selectedStage)
Then in my service i'm doing this:
service.ts
// get entities
this.http.get(`/api/entities/${jobId}/${stage}`).pipe(take(1)).subscribe((entities:IEntity[]) => {
this.entities$.next(entities)
})
// get tasks
this.http.get(`/api/tasks/${jobId}/${stage}`).pipe(take(1)).subscribe((tasks:ITask[]) => {
this.tasks$.next(tasks)
})
combineLatest(
this.entities$,
this.tasks$,
).pipe(
map(([entities, tasks]) => {
// doing some stuff here
})
).subscribe(entities => {
this.entities = entities
})
Then in my components i'm loading the data directly from the service:
html
_entityService.entities
However when I navigate between the two routes the subscriptions aren't being destroyed so I end up with multiple subscriptions. How can I correctly destroy the subscription when I navigate away from the component?
We need to add the subscription on the component, thus we can unsubscribe the subscriptions! when the component gets destroyed!
component.ts
service.ts