Angular 4+ ngOnDestroy() 服务中 - 销毁可观察对象 [英] Angular 4+ ngOnDestroy() in service - destroy observable

查看:23
本文介绍了Angular 4+ ngOnDestroy() 服务中 - 销毁可观察对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个 Angular 应用程序中,我们有一个组件/指令的 ngOnDestroy() 生命周期钩子,我们使用这个钩子来取消订阅 observables.

我想清除/销毁在 @injectable() 服务中创建的 observable.我看到一些帖子说 ngOnDestroy() 也可以在服务中使用.

但是,这是一个好的做法吗?唯一的方法是什么?什么时候会被调用?有人请澄清.

解决方案

OnDestroy 生命周期钩子是在提供者中可用.根据文档:

<块引用>

当指令、管道或服务被销毁时调用的生命周期钩子.

这是一个示例:

@Injectable()类服务实现 OnDestroy {ngOnDestroy() {console.log('服务销毁')}}@成分({选择器:'foo',模板:`foo`,提供者:[服务]})导出类 Foo 实现 OnDestroy {构造函数(服务:服务){}ngOnDestroy() {console.log('foo 销毁')}}@成分({选择器:'我的应用',模板:`<foo *ngIf="isFoo"></foo>`,})出口类应用{isFoo = 真;构造函数(){setTimeout(() => {this.isFoo = false;}, 1000)}}

注意上面代码中的Service是一个属于Foo组件的实例,所以当Foo被销毁时它可以被销毁.

对于属于根注入器的提供程序,这将在应用程序销毁时发生,这有助于避免多个引导程序(即在测试中)的内存泄漏.

当来自父注入器的提供者在子组件中订阅时,它不会在组件销毁时被销毁,这是组件有责任在组件 ngOnDestroy 中取消订阅(正如另一个答案所解释的).

In an angular application we have ngOnDestroy() lifecycle hook for a component / directive and we use this hook to unsubscribe the observables.

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 lifecycle hook is available in providers. According to the docs:

Lifecycle hook that is called when a directive, pipe or service is destroyed.

Here's an 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)
  }
}

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.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆