我会以您的 config.js 理念为基础。配置应该作为应用程序启动的一部分加载,而不是构建的一部分。您需要创建一个在应用程序启动时加载 config.js 的服务,使用 APP_INITIALIZER 提供程序并将其传递给创建服务的工厂。这是一个例子:
app.module.ts
import { NgModule, APP_INITIALIZER } from '@angular/core';
@NgModule({
imports: [
....
],
declarations: [
....
],
providers: [
{
provide: APP_INITIALIZER,
useFactory: configServiceFactory,
deps: [ConfigService, Http, AppConfig],
multi: true
},
AppConfig,
ConfigService
],
bootstrap: [AppComponent]
})
export class AppModule {
}
配置服务:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { AppConfig } from '../../app.config';
@Injectable()
export class ConfigService {
private _config: AppConfig;
constructor(private http: Http, private config: AppConfig) {
}
public Load(): Promise<AppConfig> {
return new Promise((resolve) => {
this.http.get('./config.json').map(res => res.json())
.subscribe((config: AppConfig) => {
this.copyConfiguration(config, new AppConfig()).then((data: AppConfig) => {
this._config = data;
resolve(this._config);
});
}, (error: any) => {
this._config = new AppConfig();
resolve(this._config);
});
});
}
public GetApiUrl(endPoint: any): string {
return `${this._config.ApiUrls.BaseUrl}/${this._config.ApiUrls[ endPoint ]}`;
}
public GetApiEndPoint(endPoint: any): string {
return this._config.ApiUrls[ endPoint ];
}
public Get(key: any): any {
return this._config[ key ];
}
private copyConfiguration(source: Object, destination: Object): any {
return new Promise(function(resolve) {
Object.keys(source).forEach(function(key) {
destination[ key ] = source[ key ];
resolve(destination);
});
});
}
}
export function configServiceFactory(config: ConfigService) {
return () => config.Load();
}