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) {}
}
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?
Questions:
When this component is destroyed, is the
WebsocketService
instance also destroyed?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?