puddlejumper26 / blogs

Personal Tech Blogs
4 stars 1 forks source link

Providers - useClass, useValue in Angular #14

Open puddlejumper26 opened 4 years ago

puddlejumper26 commented 4 years ago

When we talk about Providers, are usually referring Dependency Providers. Related to the DI token, and used with the Dependency Injection.

Providers are necessary for Injectors, otherwise, the Injectors won't know how to create the dependency.

Provider is an object with two properties

  1. provide property is a token key for dependency value, and configur the injector
  2. a provider definition key, could be useClass, useValue, useExisting, and useFactory.

The Provider object literal

Alternative class providers

The following code tells the injector to return a BetterLogger instance when the component asks for a logger using the Logger token.

[{ provide: Logger, useClass: BetterLogger }]

Class providers with dependencies

Aliased class providers

Value providers

It's easier to provide a ready-made object rather than ask the injector to create it from a class.

To inject an object that is already created, here is the situation for the useValue .

Non-class dependencies

Injection for string,function or object.

Factory providers

Rules for Providers

app.module.ts

@NgModule ({
  providers: [ ProductService ] 
})

is equal to 

providers: [ provide: ProductService, useClass:ProductService ]

providers is an Array , and each element inside is a provider, a provider defines how to instance an object before injected into any component.

@Injector will find the token of Service inside the construtor, then will find the provide:ProductService with the tool provided by Angular, then use the useClass to new a ProductService, here the ProductService could be differently, e.g. AnotherProductService.

Three levels for injecting Providers