angular 構建可以動態掛載的配置服務
Intro
在 angular 中可以指定 environment 來區分不同環境下的配置,然而 environment 中的配置會在打包時是固定的,想要像掛載 asp.net core 里的 appsettings.json 的配置文件一樣掛載 environment 是做不到的,想要讀取系統的環境變量也是行不通的。
有時候希望能夠動態指定一些配置,運行 docker 容器的時候掛載一個配置文件來實現動態配置
實現方案
通過一個 config.js 的配置文件,將配置信息寫入 window 對象的屬性中,配置信息從 window 對象中讀取,
這樣就可以動態掛載配置文件了。
實現細節
實現 ConfigService:
import { environment } from "../../environments/environment";
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ConfigService {
public GetApiBaseUrl(): string {
if (window["__env"] && window["__env"]["ApiBaseUrl"]) {
return <string>window["__env"]["ApiBaseUrl"];
}
return environment.apiBaseUrl;
}
}
config.js 示例:
var env = {
ApiBaseUrl: "https://reservation.weihanli.xyz"
};
window["__env"]= env;
在 index.html 中引入 config.js 文件
<script src="assets/config.js"></script>
使用 ConfigService 示例:
import { ConfigService } from './ConfigService';
export class BaseService<TModel>{
protected readonly apiBaseUrl;
constructor(config: ConfigService){
this.apiBaseUrl = config.GetApiBaseUrl();
}
}
Docker 掛載
docker run -d -p 9000:80 --name=reservation-client -v $(pwd)/assets/config.js:/usr/share/nginx/html/assets/config.js weihanli/reservation-client:latest # 掛載配置文件
sample config.js:
var env = {
ApiBaseUrl: "https://reservation.weihanli.top"
};
window["__env"]= env;
容器啟動成功之后,訪問 http://localhost:9000 即可,監控 HTTP 請求

可以看到實際請求的地址已經變成了掛載的配置文件里的地址了
