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.

1

After applying the service,

2

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

TYPES OF PROVIDERS

  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

useExisting

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

To use useExisting inside the component now,

3

useValue

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

Output:

4

 

useFactory

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!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s