角度依赖注入,服务寿命 [英] Angular dependency injection, services lifetime

查看:65
本文介绍了角度依赖注入,服务寿命的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对Angular服务的寿命存在一些疑问.我目前的理解是,如果将服务注入组件中,并且该服务在该组件的providers数组中提供,那么在销毁该组件时,该服务也将被销毁.

Having some questions regarding the lifetime of Angular services. My current understanding is that if you inject the service into a component, and the service is provided in the providers array of that component, then the service will be destroyed when the component is destroyed.

以下是一个不太抽象的示例:

Here is an example to be less abstract:

@Component({
  selector: 'app-offline-header',
  templateUrl: './offline-header.component.html',
  styleUrls: ['./offline-header.component.css'],
  providers: [WebsocketService]
})

export class OfflineHeaderComponent{ 
  constructor(private socket: WebsocketService) {}
}

在上面的示例中, WebsocketService 被注入到此组件的级别上,而不是注入到app.module(或其他模块)上.那么,如果此组件被破坏,服务实例也将被破坏吗?

In the above example the WebsocketService is injected on the level of this component and not on the app.module (or other module). So if this component is destroyed the service instance will also be destroyed?

问题:

  1. 此组件销毁后, WebsocketService 实例也销毁了吗?

如果我们要在根模块( app.module )中提供此服务,那么服务是单身吗?如果是这种情况,并且服务是一个单例,那么该单例何时创建?

If we were to provide this services in the root module (app.module), is service then a singleton? If this the case and the service is a singleton, when is this singleton created?

推荐答案

您可以阅读有关它的更多信息

You can read more about it here

回答您的问题

1-是的,它被销毁了.这完全取决于提供服务的组件的生命周期.

1- Yes, it is destroyed. It totally depends on component's lifecycle which provides the service.

请注意,组件提供的服务的寿命可能有限.组件的每个新实例都有其自己的服务实例,并且在销毁组件实例时,该服务实例也是如此.

Note that a component-provided service may have a limited lifetime. Each new instance of the component gets its own instance of the service and, when the component instance is destroyed, so is that service instance.

2-是的,它是单例并且在整个应用程序中共享.我不确定何时确切创建单例服务,但我认为它们是在组件之前创建的,以便如果组件需要服务,则可以在其构造函数中获取它.

2- Yes, it is singleton and shared throughout your application. I'm not sure when exactly singleton services are created but I think they are created before components so that if a component needs a service, it can get it within its constructor.

这篇关于角度依赖注入,服务寿命的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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