Angular Official documentation

Specifying a provider token

If you specify the service class as the provider token, the default behavior is for the injector to instantiate that class with new.

In the following example, the Logger class provides a Logger instance.

providers: [Logger]

In the providers section of the NgModule, specify the Provider token. When specifying a service class directly as a Provider token, the default behavior is that the Injector directly initialized that class with new.

In the example above, the Logger constructor is triggered. Is equivalent to:

[{ provide: Logger, useClass: Logger }]

This complete declaration, called Expanded Provider Configuration in the Angular documentation, is an object with two properties.

  • The provide property holds the token that serves as the key for both locating a dependency value and configuring the injector.

The provide property contains a token that is used to locate a Dependency Value and configure the Injector.

  • The second property is a provider definition object, which tells the injector how to create the dependency value. The provider-definition key can be useClass, as in the example. It can also be useExisting, useValue, or useFactory. Each of these keys provides a different type of dependency, as discussed below.

The second property is a Provider definition object that tells the Injector how to create dependency Value. This definition can be useClass, useExisting, useValue, or useFactory.

Some examples:

[{ provide: Logger, useClass: BetterLogger }]

When using the Logger Token, the Injector returns an instance of BetterLogger.

Aliasing class providers

To alias a class provider, specify the alias and the class provider in the providers array with the useExisting property.

In the following example, the injector injects the singleton instance of NewLogger when the component asks for either the new or the old logger. In this way, OldLogger is an alias for NewLogger.

The following configuration causes the Component to return the NewLogger singleton instance when it needs to use OldLogger. Of course, if NewLogger is requested, the NewLogger instance is returned. So in this case, OldLogger is the semantic alias for NewLogger.

[ NewLogger,
  // Alias OldLogger w/ reference to NewLogger
  { provide: OldLogger, useExisting: NewLogger}]
Copy the code