Angular 依赖注入,服务生命周期
Angular dependency injection, services lifetime
对 Angular 服务的生命周期有一些疑问。我目前的理解是,如果你将服务注入到一个组件中,并且该服务是在该组件的提供者数组中提供的,那么该服务将在组件销毁时被销毁。
下面是一个不太抽象的例子:
@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(或其他模块)。那么如果这个组件被销毁,服务实例也会被销毁?
问题:
当这个组件被销毁时,WebsocketService
实例是否也被销毁?
如果我们在根模块(app.module
)中提供这个服务,那么服务是单例吗?如果是这种情况并且服务是单例,那么这个单例是什么时候创建的?
您可以阅读更多相关信息here
回答您的问题
1- 是的,它被摧毁了。这完全取决于提供服务的组件的生命周期。
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- 是的,它是单例的并且在整个应用程序中共享。我不确定何时创建单例服务,但我认为它们是在组件之前创建的,因此如果组件需要服务,它可以在其构造函数中获取它。
对 Angular 服务的生命周期有一些疑问。我目前的理解是,如果你将服务注入到一个组件中,并且该服务是在该组件的提供者数组中提供的,那么该服务将在组件销毁时被销毁。
下面是一个不太抽象的例子:
@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(或其他模块)。那么如果这个组件被销毁,服务实例也会被销毁?
问题:
当这个组件被销毁时,
WebsocketService
实例是否也被销毁?如果我们在根模块(
app.module
)中提供这个服务,那么服务是单例吗?如果是这种情况并且服务是单例,那么这个单例是什么时候创建的?
您可以阅读更多相关信息here
回答您的问题
1- 是的,它被摧毁了。这完全取决于提供服务的组件的生命周期。
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- 是的,它是单例的并且在整个应用程序中共享。我不确定何时创建单例服务,但我认为它们是在组件之前创建的,因此如果组件需要服务,它可以在其构造函数中获取它。