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.
TYPES OF PROVIDERS
- Type Provider
- Class Provider
- Value Provider
- Existing Provider
- Factory ProviderThe syntax for using providers is :
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:
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 (https://angular-9bljze.stackblitz.io) and try yourself!