Skip to content

Angular Provider note

Dependency provider

In a nutshell, it’s a recipe which tells Angular how to create an instance of dependency.

ts
@Injetable()
export class Logger {
   log(message: string) {
      console.log(message);
   }
}

@Injectable()
export class TimeLogger extends Logger {
   override log(message: string) {
      super.log(`${(new Date()).toLocaleTimeString()}: ${message}}
   }
}

@Component({
   ...,
   providers: [ {provide: Logger, useClass: TimeLogger} ]
})
export class MyComponent {
   constructor(private readonly logger: Logger) {
      logger.log(‘Hello World’);	//5:17:35 PM: Hello World
   }
}

References