Suppose I define an interface AppConfig and an object HERO_DI_CONFIG in app.config.ts, I want to inject the latter into the constructor of a class:
export interface AppConfig {
apiEndpoint: string;
title: string;
}
import { InjectionToken } from '@angular/core';
export const APP_CONFIG = new InjectionToken<AppConfig>('app.config');
export const HERO_DI_CONFIG: AppConfig = {
apiEndpoint: 'api.heroes.com',
title: 'Dependency Injection'
};
Use InjectionToken to create a new token. The type parameter is AppConfig. App.config in single quotes is the description of the injection token.
Use useValue injection in NgModule:
Where you need to use this dependency, pass token APP_CONFIG to @Inject:
The final effect:
For more original articles by Jerry, please follow the public account "Wang Zixi":