So I have a timer where I call an api every 60 seconds (it's a digital signage app so there won't be any interaction yet I want it to auto update)
I have various components that load different api calls but the problem is, when I'm trying to unsubscribe to these timer subscriptions ondestroy it simply does not work.
I go in, test by routing to 2 components back and forth 5-6 times. This should normally kil subscription everytime I go to the next one.
After 60 seconds passes, there's as many api calls being made as many times I've switched between those two. so I've created a timer subscription everytime I went on one of the components but did not destroy them.
EDIT, added my full OnInit and OnDestroy code below:
ngOnInit() {
let mainTimer = timer(0, 60000);
this.dataSourceSubscription = mainTimer.subscribe(t => {
this.service.getSection3();
this.dataSourceSubscription = this.section3.subscribe(data => {
let countAccepted = data => {
for (let i = 0; i < data.length; i++) {
if (
data[i].DeliveryStatus == "Accepted" &&
data[i].BookingId == "0"
) {
this.multidropAccepted++;
}
}
};
let countDepartedSite = data => {
for (let i = 0; i < data.length; i++) {
if (
data[i].DeliveryStatus == "Departed Site" &&
data[i].BookingId == "0"
) {
this.multidropDepartedSite++;
}
}
};
let countPending = data => {
for (let i = 0; i < data.length; i++) {
if (
data[i].DeliveryStatus == "Pending" &&
data[i].BookingId == "0"
) {
this.multidropPending++;
}
}
};
let countOnSite = data => {
for (let i = 0; i < data.length; i++) {
if (
data[i].DeliveryStatus == "On Site" &&
data[i].BookingId == "0"
) {
this.multidropOnSite++;
}
}
};
let countTurnedAway = data => {
for (let i = 0; i < data.length; i++) {
if (
data[i].DeliveryStatus == "Turned Away" &&
data[i].BookingId == "0"
) {
this.multidropTurnedAway++;
}
}
};
(this.dataSource = new MatTableDataSource(
data.filter(
(value, index, array) =>
!array.filter(
(v, i) => JSON.stringify(value) == JSON.stringify(v) && i < index
).length
)
)),
(this.dataSource.sort = this.sort),
(this.dataSource.paginator = this.paginator),
this.multidropAccepted = 0;
this.multidropDepartedSite = 0;
this.multidropPending = 0;
this.multidropOnSite = 0;
this.multidropTurnedAway = 0;
countAccepted(data),
countDepartedSite(data),
countPending(data),
countOnSite(data),
countTurnedAway(data),
this.totalDeliveries = data.length;
});
this.lastUpdated.subscribe(data => {
console.log(data);
})
})
let pageTimer = timer(10000, 10000);
this.pageSubscription = pageTimer.subscribe(t => {
if (
this.dataSource.paginator._pageIndex ==
this.dataSource.paginator.getNumberOfPages()
) {
this.dataSource.paginator.firstPage();
} else {
this.dataSource.paginator.nextPage();
}
});
}
ngOnDestroy() {
this.dataSourceSubscription.unsubscribe();
this.pageSubscription.unsubscribe();
}
applyFilter(filterValue: string) {
this.dataSource.filter = filterValue.trim().toLowerCase();
if (this.dataSource.paginator) {
this.dataSource.paginator.firstPage();
}
}