在 Angular 应用程序中,我们为组件/指令设置了 ngOnDestroy()
生命周期 Hook ,我们使用该 Hook 取消订阅可观察对象。
我想清除/销毁在 @injectable()
服务中创建的可观察对象。
我看到一些帖子说 ngOnDestroy()
也可以用在服务中。
但是,这是一个很好的做法吗?唯一的方法是什么时候调用它? 有人请澄清。
最佳答案
OnDestroy生命周期钩子(Hook)在提供者中可用。 根据文档:
Lifecycle hook that is called when a directive, pipe or service is destroyed.
这是一个 example :
@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
被销毁的时候也可以被销毁。
对于属于根注入(inject)器的提供者,这将在应用程序销毁时发生,这有助于避免多个 Bootstrap (即在测试中)的内存泄漏。
当来自父注入(inject)器的提供者在子组件中被订阅时,它不会在组件销毁时被销毁,这是组件在组件 ngOnDestroy
中取消订阅的责任(正如另一个答案所解释的那样)。
关于服务中的 Angular 4+ ngOnDestroy() - 销毁 observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45898948/