angular2-路径更改时终止可观察间隔的最佳方法 [英] angular2 - Best way to terminate a observable interval when path changes
问题描述
我使用可观察的间隔每隔五秒钟执行某个组件中与我的路由配置中的路径相关的某个功能.
I am using an observable interval to execute an certain function every fifth second within a certain component, related to a path in my route configuration.
Observable.interval(5000).subscribe(res => {
// Something happens here
});
但是,我想在路径更改时终止间隔.现在它继续执行任务...
However I want to terminate the interval when the path changes. Now it just continues to execute the task...
做到这一点的最佳方法是什么?
What is the best way to do this?
推荐答案
在这种情况下,您可以取消订阅(订阅方法的返回对象):
You could unsubscribe from the subscription (the return object of the subscribe method) in such case:
var subscription = Observable.interval(5000).subscribe(res => {
// Something happens here
});
// to be called when the route changes
subscription.unsubscribe();
由于可观察的对象很冷,不再有订阅,因此可观察的对象将被处置...
Because the observable is cold and there will no more subscription, the observable will be disposed...
您可以利用组件中的"routerOnDesactivate"钩子方法退订.当您将路由组件留在路由上下文中时,便可以通过钩子了解到这一点.
You can leverage the "routerOnDesactivate" hook method in your component to unsubscribe. It's the hook that let you know when you leave the route component within the routing context.
有关更多详细信息,请参见此链接:
See this link for more details:
这篇关于angular2-路径更改时终止可观察间隔的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!