Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 useExisting providers

What are the usages for useExisting provider?

Is it useExistingOrThrowIfThereIsNone or useExistingOrCreateIfThereIsNone? Can one of these behaviours be chosen on purpose somehow, depending on our needs? If one of them is not supported, can an unsupported one be emulated?

The documentation is totally unclear on that and just gives an example that useExisting can reuse an instance from useClass.

like image 218
Estus Flask Avatar asked Jul 17 '16 11:07

Estus Flask


People also ask

What are providers in Angular 2?

Providers are classes that create and manage service objects the first time that Angular needs to resolve a dependency. Providers is used to register the classes to an angular module as a service. And then, this service classes can be used by other components during the itself creation phase in the module.

What are the types of providers in Angular?

There are four ways by which you can create the dependency: They are Class Provider (useClass), Value Provider (useValue ), Factory Provider ( useFactory ), and Aliased Class Provider ( useExisting).

What is useExisting in Angular?

The useExisting provider key lets you map one token to another. In effect, the first token is an alias for the service associated with the second token, creating two ways to access the same service object.

What is dependency provider in Angular?

A dependency provider configures an injector with a DI token, which that injector uses to provide the concrete, runtime version of a dependency value. The injector relies on the provider configuration to create instances of the dependencies that it injects into components, directives, pipes, and other services.


1 Answers

With this example

providers: [
    A, 
    {provide: B, useClass: A}, 
    {provide: C, useExisting: A}]

If you have

constructor(private a: A)

an instance for the first provider is created.

constructor(private b: B)

an instance for the 2nd provider is created

constructor(private c: C)

the instance of the first provider is injected.

If you start fresh with

constructor(private c: C)

an instance for the first provider is created and injected

like image 81
Günter Zöchbauer Avatar answered Oct 06 '22 23:10

Günter Zöchbauer