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?
In Angular 13 Framework, the services are those objects that get instantiated a maximum of one time during the entire lifetime of any Angular application or Angular module. All the Angular Services contain many methods that maintain data throughout the lifetime of an application.
There are three lifetimes that can be used with Microsoft Dependency Injection Container, they are: Transient — Services are created each time they are requested. It gets a new instance of the injected object, on each request of this object.
The main objective of angular services is to share data across Angular application. Practically an angular service can be shared between all the components or can be limited to some component. Hence Angular service can be a singleton as well as non-singleton in nature.
Angular provides the ability for you to inject a service into a component to give that component access to the service. The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency.
You can read more about it here
To answer your questions
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- 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With