Angular 4+ ngOnDestroy()在使用中-销毁可观察到的 [英] Angular 4+ ngOnDestroy() in service - destroy observable
问题描述
在有角度的应用程序中,我们为组件/指令提供了ngOnDestroy()
生命周期钩子,并使用该钩子取消了对可观察对象的订阅.
In an angular application we have ngOnDestroy()
lifecycle hook for a component / directive and we use this hook to unsubscribe the observables.
我想清除/破坏在@injectable()
服务中创建的可观察性.
我看到一些帖子说ngOnDestroy()
也可以在服务中使用.
I want to clear / destory observable that are created in an @injectable()
service.
I saw some posts saying that ngOnDestroy()
can be used in a service as well.
但是,这是一个好习惯吗,并且是唯一的方法,何时才能调用它? 有人请澄清.
But, is it a good practice and only way to do so and When will it get called ? someone please clarify.
推荐答案
OnDestroy 生命周期挂钩是在提供程序中可用. 根据文档:
OnDestroy lifecycle hook is available in providers. According to the docs:
销毁指令,管道或服务时调用的生命周期挂钩.
Lifecycle hook that is called when a directive, pipe or service is destroyed.
这是一个示例:
@Injectable()
class Service implements OnDestroy {
ngOnDestroy() {
console.log('Service destroy')
}
}
@Component({
selector: 'foo',
template: `foo`,
providers: [Service]
})
export class Foo implements OnDestroy {
constructor(service: Service) {}
ngOnDestroy() {
console.log('foo destroy')
}
}
@Component({
selector: 'my-app',
template: `<foo *ngIf="isFoo"></foo>`,
})
export class App {
isFoo = true;
constructor() {
setTimeout(() => {
this.isFoo = false;
}, 1000)
}
}
请注意,在Service
上面的代码中,它是属于Foo
组件的一个实例,因此可以在销毁Foo
时销毁它.
Notice that in the code above Service
is an instance that belongs to Foo
component, so it can be destroyed when Foo
is destroyed.
对于属于根注入器的提供程序,这将在应用程序销毁时发生,这有助于避免使用多个引导程序(即在测试中)导致内存泄漏.
For providers that belong to root injector this will happen on application destroy, this is helpful to avoid memory leaks with multiple bootstraps, i.e. in tests.
当父注入者的提供者在子组件中被订阅时,它不会在组件销毁时被销毁,这是组件有责任在组件ngOnDestroy
中退订(如另一个答案所解释).
When a provider from parent injector is subscribed in child component, it won't be destroyed on component destroy, this is component's responsibility to unsubscribe in component ngOnDestroy
(as another answer explains).
这篇关于Angular 4+ ngOnDestroy()在使用中-销毁可观察到的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!