Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - stopping 'setInterval' http requests on route change

I'm writing a realtime updating graph using Angular2. My graph is being updated through data coming via an http observable, and a setInterval command.

A weird thing I've noticed is that, when I route through angular to a different view on my app, the setInterval command on the previous component does not stop, causing the server for unnecessary load.

What would be the correct method to stop setInterval http requests on route changes in Angular2?

Any help would appreciated.

like image 552
Omer Kushmaro Avatar asked Apr 03 '16 14:04

Omer Kushmaro


1 Answers

Events are managed very differently by browsers, basically they are processed by Event loop.

The browser has inner loop, called Event Loop, which checks the queue and processes events, executes functions etc.

So whenever you add any asynchronous event like setTimeout/setInterval, they gets added to Event Loop with their handlers.

Basically whenever you wanted to stop/de-register those asynchronous event, you need to de-register them manually. Like here you need to call clearInterval method with that setInterval object reference, then only it will remove that async event from Event Loop.

You could use ngOnDestroy life-cycle hook where you can have your stuff before destroying your component.

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

Extra stuff(Comparing with Angular 1)

The same kind of problem you can see in any Javascript Framework. In Angular 1 there is way to handle such kind of situation(I'm adding this stuff so that anyone from Angular 1 background can easily get this concept by comparing A1 with A2). While destroying controller instance angular internally emit's $destroy event over element & $scope of that element. So by having listener over $destroy event, we used to do stuff to ensure those object value/object/events should not available.

$scope.$on('$destroy', function(event){
   //do stuff here
})

element.bind('$destroy', function(event){
   //do stuff here
})
like image 130
Pankaj Parkar Avatar answered Oct 17 '22 08:10

Pankaj Parkar