问题描述
对 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?
问题:
当这个组件被销毁时,
WebsocketService
实例是否也被销毁了?
When this component is destroyed, is the
WebsocketService
instance also destroyed?
如果我们在根模块 (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.
请注意,组件提供的服务可能具有有限的生命周期.组件的每个新实例都有自己的服务实例,当组件实例被销毁时,该服务实例也会被销毁.
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.
这篇关于Angular 依赖注入,服务生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!