首页 > 其他 > 详细

angular 构建可以动态挂载的配置服务

时间:2020-01-26 11:57:34      阅读:106      评论:0      收藏:0      [点我收藏+]

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

angular 构建可以动态挂载的配置服务

原文:https://www.cnblogs.com/weihanli/p/12234002.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!