angular 構建可以動態掛載的配置服務


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 請求

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

Reference


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM