Angular dependency injection, services lifetime
Asked Answered
A

1

6

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:

  1. When this component is destroyed, is the WebsocketService instance also destroyed?

  2. 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?

Alee answered 5/5, 2018 at 10:31 Comment(0)
R
8

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.

Railey answered 5/5, 2018 at 10:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.