这是一个非常好的问题,我们也有不同的服务器(Dev、QC、Stage、Prod),
因此为每个环境创建单独的构建是非常耗时的过程,
我从未尝试过为每个环境创建单独的环境文件的这种方法,
我们通过将 Api Urls 和常量存储在 json 文件中解决了这个问题。
首先创建一个 json 文件并将其放在 assets 文件夹中。
Config.json
{
"url":{
"apiUrl": "http://localhost:58357/"
}
}
创建一个模型类,其属性应与 Config.json 文件具有相同名称
Config.ts
export class Config {
url: {
apiUrl: string;
};
}
创建服务以导入 Config.json 文件
app.config.service.ts
import { Injectable } from '@angular/core';
import { Config } from './models/config';
import { HttpClient, HttpBackend, HttpResponse } from '@angular/common/http';
import { Observable } from '../node_modules/rxjs';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class AppConfig {
static Settings: Config;
private http: HttpClient;
constructor(private httpBackEnd: HttpBackend) {
this.http = new HttpClient(httpBackEnd);
}
load() {
const jsonFile = 'assets/config.json';
return new Promise<void>((resolve, reject) => {
this.http.get(jsonFile).toPromise().then((response: Config) => {
AppConfig.Settings = <Config>response;
resolve();
}).catch((response: any) => {
reject(`Could not load file '${jsonFile}': ${JSON.stringify(response)}`);
});
});
}
}
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { AppComponent } from './app.component';
import { AppConfig } from '../app.config.service';
import { HttpClientModule } from '../../node_modules/@angular/common/http';
export function initConfig(appConfig: AppConfig) {
return () => appConfig.load();
}
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
],
providers: [
AppConfig, { provide: APP_INITIALIZER, useFactory: initConfig, deps: [AppConfig], multi: true },
],
bootstrap: [AppComponent]
})
export class AppModule { }
在您想要使用存储在 json 文件中的密钥的任何组件文件中导入 AppConfig。
app.component.ts
import { Component } from '@angular/core';
import { AppConfig } from '../app.config.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'ConstantsManagerDemo';
constructor() {
const apiUrl = AppConfig.Settings.url.apiUrl;
alert(apiUrl);
}
}
转到 tsconfig.json 文件并添加
"allowSyntheticDefaultImports" :true,
under compilerOptions