Currently, I have a sidebar that allows me to click on individual components. These components refresh API calls to get data. However, when I click off the components to another component, the old component keeps on refreshing API data, even though it is not needed as I have clicked off from it.
Here is a test component below. It prints out "test component is still active" when I click on the component. When I click off the component to another component, it still says "test component is still active", this tells me that the component is still running. Is there a way to turn off the component once I have clicked off it? Or is there a better way of getting fresh data?
export class TestComponent implements OnInit {
userActivity;
constructor(
) { }
ngOnInit() {
this.refreshData();
}
refreshData(){
this.userActivity = setTimeout(() => {
// where api data is called out
console.log('test component is still active');
this.refreshData();
}, 5000);
}
}
CodePudding user response:
This is a very common problem when dealing with asynchronous code such as subscriptions or setTimeout()
inside Angular components. Angular doesn't unsubscribe or "kill" such asynchronous code automatically - you have to take care of it.
There are various ways to handle this depending on the specific problem. In your case, you already store the handle which is returned from setTimeout
in userActivity
. You can take this handle and clear the timeout inside Angular's OnDestroy lifecycle hook. Think of OnDestroy
as the counterpart of OnInit
, it gets called when a component gets destroyed.
export class TestComponent implements OnInit, OnDestroy {
userActivity;
constructor() {}
ngOnInit() {
this.refreshData();
}
refreshData() {
this.userActivity = setTimeout(() => {
// where api data is called out
console.log('test component is still active');
this.refreshData();
}, 1000);
}
ngOnDestroy() {
clearTimeout(this.userActivity);
}
}
You can see it in action in this Stackblitz. If you look at the console output, you should see that your console.log is no longer logged as soon as you switch from component 1 to component 2.