Angular2 is the best way to end the observed interval when the path changes

I use the observed interval to perform a specific function every fifth second inside a specific component associated with the path in my route configuration.

Observable.interval(5000).subscribe(res => { // Something happens here }); 

However, I want to end the interval when the path changes. Now he just continues the task ...

What is the best way to do this?

+6
angular typescript observable
source share
2 answers

You can unsubscribe (the object of returning the subscription method) in this case:

 var subscription = Observable.interval(5000).subscribe(res => { // Something happens here }); // to be called when the route changes subscription.unsubscribe(); 

Since the observed cold and there will be no more subscription, the observed will be located ...

You can use the hook method "routerOnDesactivate" in your component to unsubscribe. This is a hook that lets you know when you leave a route component in the routing context.

See this link for more details:

+4
source share

A great way to solve this problem is to create an observable in a variable and use '| async 'to sign and show the value in the template. Unsubscribing, everyone takes care of this through the pipe.

0
source share