Loading

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

posted @ 2020-01-26 11:48  WeihanLi  阅读(789)  评论(1编辑  收藏  举报