我正在开发一个 Angular 应用程序,它是一个产品并部署到多个客户端。客户将使用这个 Angular 应用程序并将其托管在他们的服务器中。因此服务的 url 将因客户而异。我见过谈论开发、生产的解决方案。但这不适用于这种情况。我正在寻找类似于 .net 配置文件的配置文件。我已经创建了一个单独的 app.config.ts 文件,但是在我构建时会构建它。我正在寻找一种解决方案,我可以将应用程序部署到任何客户端,而无需他们重新构建它。
import { InjectionToken } from "@angular/core";
export let APP_CONFIG = new InjectionToken("app.config");
export interface IAppConfig {
apiEndpoint: string;
}
export const AppConfig: IAppConfig = {
apiEndpoint: "http://88.87.86.999/"
};
最佳答案
你可以做什么它在 Assets 文件夹中托管 json 格式的配置文件并动态检索它。您需要确保在应用程序启动之前检索它,这样它就可以在组件/服务需要时可用。为此,您可以使用 APP_INITIALIZER token
第一步:把你的json配置文件放在src/assets/config/conf.json下(json格式,不是ts格式,因为prod模式下没有TS编译器)
第 2 步:添加新的配置服务
import {Inject, Injectable} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {Observable} from 'rxjs/Rx';
import {environment} from "../../environments/environment";
/**
* Declaration of config class
*/
export class AppConfig
{
//Your properties here
readonly apiEndpoint: string;
}
/**
* Global variable containing actual config to use. Initialised via ajax call
*/
export let APP_CONFIG: AppConfig;
/**
* Service in charge of dynamically initialising configuration
*/
@Injectable()
export class AppConfigService
{
constructor(private http: HttpClient)
{
}
public load()
{
return new Promise((resolve, reject) => {
this.http.get('/assets/config/config.json').catch((error: any): any => {
reject(true);
return Observable.throw('Server error');
}).subscribe((envResponse :any) => {
let t = new AppConfig();
//Modify envResponse here if needed (e.g. to ajust parameters for https,...)
APP_CONFIG = Object.assign(t, envResponse);
resolve(true);
});
});
}
}
第 3 步:在您的主模块中,在声明模块之前添加它
/**
* Exported function so that it works with AOT
* @param {AppConfigService} configService
* @returns {Function}
*/
export function loadConfigService(configService: AppConfigService): Function
{
return () => { return configService.load() };
}
第 4 步:修改模块提供者以添加此内容
providers: [
…
AppConfigService,
{ provide: APP_INITIALIZER, useFactory: loadConfigService , deps: [AppConfigService], multi: true },
],
第 5 步:在您的代码中,使用配置
import {APP_CONFIG} from "../services/app-config.service";
//…
return APP_CONFIG.configXXX;
现在,您可以将应用发送给多个客户;每个客户端只需要在 conf.json 文件中有他们的特定参数
关于Angular5:将 Angular 应用程序部署到多个客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49559009/