微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐