Angular 5中如何将服务配置参数注入到environment.ts中
把SettingsProvider的配置注入到Angular环境变量的方案
我来帮你搞定这个问题——你已经通过APP_INITIALIZER实现了启动前加载VSTS的配置到SettingsProvider,现在要把这些配置同步到environment变量里,其实核心就是在配置加载完成后,动态修改environment这个对象,因为它本质上就是一个普通的JS对象,运行时是可以修改的。
具体步骤来啦:
先给SettingsProvider加个获取配置的公共方法
首先得让外部能拿到SettingsProvider里加载好的配置,所以给它加个getConfig()方法:@Injectable() export class SettingsProvider { private config: any; constructor(private http: HttpClient) {} loadConfig(): Promise<any> { return this.http.get('/your-vsts-config-path.json') .toPromise() .then(config => { this.config = config; }); } // 新增这个方法,让外部能获取加载后的配置 getConfig(): any { return this.config; } }修改APP_INITIALIZER的工厂函数,同步配置到environment
在app.module.ts里,修改你的初始化函数,等配置加载完成后,把需要的参数赋值给environment:import { environment } from '../environments/environment'; export function init(settingsProvider: SettingsProvider) { return () => settingsProvider.loadConfig() .then(() => { const loadedConfig = settingsProvider.getConfig(); // 按需把配置项注入到environment里,比如你需要的api地址、版本号等 environment.apiBaseUrl = loadedConfig.apiBaseUrl; environment.appDebugMode = loadedConfig.appDebugMode; // 其他需要同步的参数照着加就行 // 如果想批量合并,也可以用Object.assign: // Object.assign(environment, loadedConfig); // 注意:批量合并会覆盖environment里同名的属性,按需选择 }); } @NgModule({ // ...你的其他模块配置 providers: [ SettingsProvider, { provide: APP_INITIALIZER, useFactory: init, deps: [SettingsProvider], multi: true } ] }) export class AppModule { }验证一下效果
现在你在任何组件或服务里用environment,就能拿到从VSTS加载的动态配置了:import { environment } from '../environments/environment'; @Component({ selector: 'app-home', templateUrl: './home.component.html' }) export class HomeComponent { ngOnInit() { console.log('当前API地址:', environment.apiBaseUrl); // 这里输出的就是从VSTS加载的配置值啦 } }
几个小提醒:
- 别全量覆盖
environment,保留它原本的编译时配置(比如production字段),只同步你需要的动态参数就行。 - 因为
APP_INITIALIZER是在应用启动前执行的,所以完全不用担心组件初始化时environment还没更新的问题,所有依赖environment的代码都会拿到最新值。
内容的提问来源于stack exchange,提问作者dave0688
相关产品推荐
相关产品推荐

