Angular2 - stop setInterval HTTP requests when changing a route

I am writing a real time chart using Angular2. My graph is updated through the data coming in through the http observable and setInterval .

It is strange that I noticed that when I go through angular to another view in my application, the setInterval command on the previous component does not stop, which leads to unnecessary server loading.

What would be the correct method to stop setInterval http requests when changing a route in Angular2?

Any help would be appreciated.

+5
source share
1 answer

Events are handled differently by browsers , they are mainly handled by the event loop .

The browser has an internal loop called Event Loop that checks the queue and processes events, performs functions, etc.

Therefore, whenever you add an asynchronous event, such as setTimeout / setInterval , they are added to the Event Loop using their handlers.

Basically, when you wanted to stop/de-register those asynchronous events, you need to uninstall them manually. As here, you need to call the clearInterval method with this setInterval object reference, then only it will remove this async event from the Event Loop .

You can use the ngOnDestroy hook where you can use your materials before destroying your component.

 //hook gets called before Component get destroyed or you can say disposed. ngOnDestroy(){ clearInterval(intervalReference) } 

Additional Resources (Comparison with Angular 1)

The same problem you can see in any Javascript Framework. Angular 1 has a way to deal with this situation (I am adding this material so that any of the Angular 1 backgrounds can easily get this concept by comparing A1 with A2 ). By destroying the controller instance of Angular from within the $destroy event, the element and $scope events of this element. Thus, having a listener over the $destroy event, we used material to ensure that the value/object/events was not accessible.

 $scope.$on('$destroy', function(event){ //do stuff here }) element.bind('$destroy', function(event){ //do stuff here }) 
+5
source

Source: https://habr.com/ru/post/1246338/


All Articles