• Angular 8 配置文件


    给Angular 8 client 添加 json 配置文件,用来存储:版本号,WebApi 地址等等。要求 json 文件必须在页面访问 webapi 前获得到,不然数据服务中无法获得配置的 WebApi 地址。

    1. 创建配置文件

    你可以在 assets 目录下创建配置文件,也可以自己创建一个目录。这里我在 src 目录下创建了一个 config 目录,用来存放 开发和 发布两个环境下的配置文件

    文件内容如下:

       

    development.json, 用来配置开发环境变量, production.json 用来配置发布环境变量

    2. 创建一个config.service.ts 文件, 用来定义个config 模块 

    模块作用:

    • 根据当前运行环境,自动加载 developement.json 或者product.json 下的内容到一个 json 对象
    • 将 config 配置成程序启动需要初始化的对象
    • 提供 get 方法,访问配置文件对象的值 
    import { Injectable, APP_INITIALIZER } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { Observable } from 'rxjs';
    import { environment } from '../../environments/environment';


    @Injectable()
    export class ConfigService {

      private _config: Object
      private _env: string;

      constructor(private http: HttpClient) { }

      load() {
        return new Promise((resolve, reject) => {
          this._env = 'development';
          if (environment.production)
            this._env = 'production';
          console.log(this._env)
          this.http.get('./config/' + this._env + '.json')
            .subscribe((data) => {
              this._config = data;
              resolve(true);
            },
              (error: any) => {
                console.error(error);
                return Observable.throw(error || 'Server error');
              });
        });
      }  

      // Gets a value of specified property in the configuration file
      get(key: any) {
        return this._config[key];
      }
    }

    export function ConfigFactory(config: ConfigService) {
      return () => config.load();
    }

    export function init() {
      return {
        provide: APP_INITIALIZER,
        useFactory: ConfigFactory,
        deps: [ConfigService],
        multi: true
      }
    }

    const ConfigModule = {
      init: init
    }

    export { ConfigModule };

    3. 在 app.module.ts 中,引用配置 config 模块

    import { ConfigModule, ConfigService } from './services/config.service';

     

     4. 在 数据服务中,获取配置

    注意:

    如果你跟我一样是在 assets 目录外创建的 配置文件或者目录,那么在运行时,你可能遇到找不到配置文件的问题。那是因为Angular 会自动把 assets 当做资源目录,而我们新创建的目录、文件并不会作为资源目录。

    你需要在 angular.json 中将你自己创建的资源目录或文件指定一下:

  • 相关阅读:
    JavaScript WebSocket C# SuperSocket.WebSocket 示例
    Nginx 配置
    Temporary Post Used For Theme Detection (272f6d70fb8946f3a568afd3d7b053bd 3bfe001a32de4114a6b44005b770f6d7)
    SpringBoot多数据源事务解决方案
    SpringBoot集成mybatis拦截器修改表名
    点击各个按钮,在执行操作之前出现确认提示框
    incoming change和current change
    Expected Number with value 8, got String with value "8".
    正则只能输入数字遇到的问题
    Antd 4.19 Modal + Form;打开modal时使用setFieldsValue,首次回显正常,第二次无效?
  • 原文地址:https://www.cnblogs.com/crdanding/p/12097543.html
Copyright © 2020-2023  润新知