简体   繁体   English

角度依赖注入,服务生命周期

[英]Angular dependency injection, services lifetime

Having some questions regarding the lifetime of Angular services. 对Angular服务的生命周期有一些疑问。 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. 我目前的理解是,如果将服务注入组件,并且该组件的providers数组中提供了服务,则在销毁组件时将销毁该服务。

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) {}
}

In the above example the WebsocketService is injected on the level of this component and not on the app.module (or other module). 在上面的示例中, WebsocketService是在此组件的级别上注入的,而不是在app.module(或其他模块)上。 So if this component is destroyed the service instance will also be destroyed? 因此,如果该组件被销毁,服务实例也将被销毁?

Questions: 问题:

  1. When this component is destroyed, is the WebsocketService instance also destroyed? 当该组件被销毁时, WebsocketService实例是否也被销毁?

  2. If we were to provide this services in the root module ( app.module ), is service then a singleton? 如果我们要在根模块( app.module )中提供这些服务,那么服务是单例吗? If this the case and the service is a singleton, when is this singleton created? 如果这个案例和服务是单身,那么这个单身人士何时被创造?

You can read more about it here 你可以在这里阅读更多相关信息

To answer your questions 回答你的问题

1- Yes, it is destroyed. 1-是的,它被摧毁了。 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- Yes, it is singleton and shared throughout your application. 2-是的,它是单身并在整个应用程序中共享。 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. 我不确定何时创建单独的单件服务,但我认为它们是在组件之前创建的,因此如果组件需要服务,它可以在其构造函数中获取它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM