Dependency Injection
Angular has built-in support for dependency injection.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class HeroService {
constructor() {}
}
Dependency Providers
providedIn
root
— application level.any
— provide a unique instance in each lazy loaded module.platform
— provide a single instance for all applications on the page.
Injection Tokens
Angular uses Injection Tokens to identify dependencies.
export const HERO_SERVICE_TOKEN = new InjectionToken<CoursesService>(
'HERO_SERVICE_TOKEN'
);
Providers
TypeProvider
ValueProvider
ClassProvider
ConstructorProvider
ExistingProvider
FactoryProvider
Factory Provider
useFactory
— invoked to create the instance with resolved values ofdeps
.deps
— list of tokes the factory depended on creating the instance.
@NgModule({
imports: [],
declarations: [],
providers: [
{
provide: HERO_SERVICE_TOKEN,
useFactory: heroServiceProviderFactory,
deps: [HttpClient],
},
],
})
export class HeroModule {}