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 中将你自己创建的资源目录或文件指定一下:

原文地址:https://www.cnblogs.com/crdanding/p/12097543.html