Angular Provider useValue over 直接使用常量

问题描述

"export const HERO_DI_CONfig: AppConfig = {
  apiEndpoint: 'api.heroes.com',title: 'Dependency Injection'
};"

示例 1: Provider 之一是 useValue

providers: [{ provide: APP_CONfig,useValue: HERO_DI_CONfig }]

constructor(@Inject(APP_CONfig) config: AppConfig) {
  this.title = config.title;
}

示例 2: 直接从 App.Config 导入 APP_CONfig 常量 并像这样使用:

let varibaleName = HERO_DI_CONfig.apiEndpoint;

使用 useValue 比直接从 App.config 访问 Constant 有什么优势

解决方法

在库(或共享功能模块)的上下文中,最好使用令牌注入器,因为它可能会过载,因此它比常量更灵活。

有许多库使用这种方法来重载常量(angular/fire 等)。