zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    sha256 in C language
    制作带动画效果的状态栏
    带进度条的任务栏
    在状态栏中显示当前系统时间
    在状态栏中显示当前操作员
    在状态栏中显示复选框
    设计浮动工具栏
    可以拉伸的菜单
    任务栏托盘菜单
    带历史信息的菜单
  • 原文地址:https://www.cnblogs.com/weihanli/p/12234002.html
Copyright © 2011-2022 走看看