Tho.Tra
Tho.Tra

Reputation: 145

When does a service get created by dependency injection

I have an angular service containing some init code in its constructor. When is this code called, i.e. when is the service created?

Upvotes: 2

Views: 1485

Answers (3)

jSebestyén
jSebestyén

Reputation: 1806

Taken from the official docs:

When Angular discovers that a component depends on a service, it first checks if the injector has any existing instances of that service. If a requested service instance doesn't yet exist, the injector makes one using the registered provider, and adds it to the injector before returning the service to Angular.

When all requested services have been resolved and returned, Angular can call the component's constructor with those services as arguments.

So it seems that a service is only instantiated when it is needed the first time.

In fact Angular even recognizes if the service will never be used and remove it from the build if it is not needed (taken from here and here).

Test it for yourself

An easy test to verify this would be to put console.logs in both a component and a service that it depends upon to see in which order the are called.

Upvotes: 4

Miguel Pinto
Miguel Pinto

Reputation: 563

If you reference on the module, the service run the constructor before components need,

@NgModule({
  providers: [
  TestService],
 ...
})

If you reference on the component, the service create a new instance for the component

@Component({
  selector:    'app-xpto',
  templateUrl: './xpto.html',
  providers:  [ TestService ]
})

Upvotes: 1

pk_teckie
pk_teckie

Reputation: 147

Until the first component injects it, go throgh below link.

When Angular creates a new instance of a component class, it determines which services or other dependencies that component needs by looking at the constructor parameter types.

https://angular.io/guide/architecture-services

Upvotes: 2

Related Questions