Dependency Injection

Angular has built-in support for dependency injection.

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class HeroService {
  constructor() {}
}

Dependency Providers

Injection Tokens

Angular uses Injection Tokens to identify dependencies.

export const HERO_SERVICE_TOKEN = new InjectionToken<CoursesService>(
  'HERO_SERVICE_TOKEN'
);

Providers

Factory Provider

@NgModule({
  imports: [],
  declarations: [],
  providers: [
    {
      provide: HERO_SERVICE_TOKEN,
      useFactory: heroServiceProviderFactory,
      deps: [HttpClient],
    },
  ],
})
export class HeroModule {}