Providers in Angular


We have learnt the concept of Services and Dependency injection in our previous article. Read here:Ā Understanding Services and Dependency injection

When we inject a service, the Angular injector needs to look at the Service providers to create an instance of that particular service.Ā  The provider determines which instance of the service should be injected at the runtime in the component, module, pipe or directive.

To understand, let us create a service first.

Inside the component,

Here, we imported the service, injected it and used it inside the component to log the hello message. Also, we provided the injected service inside the providers array. Let us look at the output.


After applying the service,


A providers therefore, determines that how the object of a particular token is created.


  1. Type Provider
  2. Class Provider
  3. Value Provider
  4. Existing Provider
  5. Factory ProviderThe syntax for using providers is :

providers: [{
provide: HelloService, useClass: HelloService

The provide property here is used for locating the dependency value and registering the dependency. On the other hand, the second parameterĀ  has 4 different values:

  1. useClass
  2. useExisting
  3. useValue
  4. useFactory


This is used to avoid creating two instances of the same Service. Inside the new service,

To use useExisting inside the component now,



When we do not want to create an instance but pass the object directly, we use useValue.Ā





When the information about our dependency is dynamic, that is when useFactory comes into play.

Here, when the value of i equals 0, the output comes from the first service, i.e., HelloService, in any other case, the output comes from the second service, i.e., NewService.

To see the working of what we just created , go to my project here on Stackblitz ( and try yourself!

Leave a comment

Your email address will not be published. Required fields are marked *