給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 中將你自己創建的資源目錄或文件指定一下: