如何解决使用文件配置生产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文件,我们可以访问它!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。