The problem:
My app is working fine on the first component I load, and when I click to switch to another component, it creates another subscription on My DAL.
Code
servers.component.html <- the default component
<div class="row">
<div class="col-md-12">
<app-server-list></app-server-list>
</div>
<router-outlet></router-outlet>
</div>
server-backup.component.html
<div class="row">
<div class="col-md-12">
<app-server-list ></app-server-list>
</div>
</div>
In server-list.component.ts I want to refresh the data from the DB every 5 seconds, so I do this:
this.dataStorageService.getServerPerformanceInfo()
this.interval = setInterval(() =>
{
this.dataStorageService.getServerPerformanceInfo()
} , 5000)
When I switch between servers and servers-backup I unsubscribe:
ngOnDestroy()
{
this.subscriptions.forEach(subscription => {
subscription.unsubscribe();
});
clearInterval(this.interval);
}
And finally on my data-storage-service.ts
getServerPerformanceInfo()
{
this.serverPerfSub = this.http.get<ServerPerformance[]>(DEV + '/getServerPerformance').subscribe
(
(data) => {
this.serversService.setPerformanceInfo(data);
}
)
}
As I switch between my components, the server-list component gets destroyed, created, but the dataStorageService calls get more and more frequent until my API method starts failing.
Surely this has to do with the subscribe on the dataStorageService, but how do I clean that?