问题描述
我发现许多示例,其中ActivatedRoute
诸如params
或url
的可观察对象已订阅但未取消订阅.
I find many examples where ActivatedRoute
Observables like params
or url
are subscribed but not unsubscribed.
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.params
// (+) converts string 'id' to a number
.switchMap((params: Params) => this.service.getHero(+params['id']))
.subscribe((hero: Hero) => this.hero = hero);
}
- 是否为每次创建组件自动销毁了路由对象和订阅并重新创建了它们?
- 我是否需要考虑退订那些
Observable
? - 如果没有,您能否解释
Router
.routerState
中的ActivatedRoute对象树的情况? - Are the route objects and subscriptions destroyed automagically and newly created for every component creation?
- Do I have to care about unsubscribing from those
Observable
s? - If not, can you explain what happens with the tree of ActivatedRoute objects in
Router
.routerState
?
推荐答案
从文档中:
订阅组件中的可观察对象时,几乎总是在组件被破坏时取消订阅.
When subscribing to an observable in a component, you almost always arrange to unsubscribe when the component is destroyed.
有一些不需要观察的例外观察点.可观察到的ActivatedRoute除外.
There are a few exceptional observables where this is not necessary. The ActivatedRoute observables are among the exceptions.
ActivatedRoute及其可观察值与路由器本身绝缘.当不再需要路由组件并且注入的ActivatedRoute随之死亡时,Router会销毁它.
The ActivatedRoute and its observables are insulated from the Router itself. The Router destroys a routed component when it is no longer needed and the injected ActivatedRoute dies with it.
随时可以退订.这是无害的,绝不是坏习惯.
Feel free to unsubscribe anyway. It is harmless and never a bad practice.
这篇关于我是否必须取消订阅ActivatedRoute(例如params)可观察对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!