使用文件配置生产 Angular 应用程序
Configuring a production Angular application with file
我必须构建一个概念验证 angular 应用程序,它将对应用程序(软件)进行 API 调用。
我的问题是我正在本地应用程序上测试调用,而客户应用程序可能有不同的设置:不同的入口点、不同的端口等。
我希望能够定义这些参数并从生产服务器上的文件中读取它们。
我阅读了有关使用环境文件的信息,但我必须在构建应用程序之前进行设置。我希望能够在之后完成。
我终于发现这里是要遵循的步骤:
https://juristr.com/blog/2018/01/ng-app-runtime-config/#runtime-configuration
1.创建服务
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class AppConfigService {
private appConfig;
constructor(private http: HttpClient) { }
loadAppConfig() {
return this.http.get('/assets/data/appConfig.json')
.toPromise()
.then(data => {
this.appConfig = data;
});
}
getConfig() {
return this.appConfig;
}
}
**2。在 app.module 中导入此服务 + 创建初始化函数 **
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { AppConfigService } from './app-config.service';
const appInitializerFn = (appConfig: AppConfigService) => {
return () => {
return appConfig.loadAppConfig();
};
};
@NgModule({
...
providers: [
AppConfigService,
{
provide: APP_INITIALIZER,
useFactory: appInitializerFn,
multi: true,
deps: [AppConfigService]
}
],
...
})
export class AppModule { }
在我的 app.component 中:
constructor(private appConfig: AppConfigService) {
}
ngOnInit(): void {
this.myConfig = this.appConfig.getConfig();
}
现在我可以在模板或应用程序的任何地方显示配置数据。构建时,json文件也被导出,我们可以访问它!
我必须构建一个概念验证 angular 应用程序,它将对应用程序(软件)进行 API 调用。 我的问题是我正在本地应用程序上测试调用,而客户应用程序可能有不同的设置:不同的入口点、不同的端口等。
我希望能够定义这些参数并从生产服务器上的文件中读取它们。 我阅读了有关使用环境文件的信息,但我必须在构建应用程序之前进行设置。我希望能够在之后完成。
我终于发现这里是要遵循的步骤: https://juristr.com/blog/2018/01/ng-app-runtime-config/#runtime-configuration
1.创建服务
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class AppConfigService {
private appConfig;
constructor(private http: HttpClient) { }
loadAppConfig() {
return this.http.get('/assets/data/appConfig.json')
.toPromise()
.then(data => {
this.appConfig = data;
});
}
getConfig() {
return this.appConfig;
}
}
**2。在 app.module 中导入此服务 + 创建初始化函数 **
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { AppConfigService } from './app-config.service';
const appInitializerFn = (appConfig: AppConfigService) => {
return () => {
return appConfig.loadAppConfig();
};
};
@NgModule({
...
providers: [
AppConfigService,
{
provide: APP_INITIALIZER,
useFactory: appInitializerFn,
multi: true,
deps: [AppConfigService]
}
],
...
})
export class AppModule { }
在我的 app.component 中:
constructor(private appConfig: AppConfigService) {
}
ngOnInit(): void {
this.myConfig = this.appConfig.getConfig();
}
现在我可以在模板或应用程序的任何地方显示配置数据。构建时,json文件也被导出,我们可以访问它!