Reputation: 1489
I have to build a proof of concept angular app that will make API calls to an application (software). My issue is that i'm testing calls on a local application and the customer application may have different settings : different entry points, different ports, etc.
I would like to be able to define those parameters and read them from a file on a production server. I read about using environment files but i have to make the setup before building the app. I want to be able to make it after.
Upvotes: 0
Views: 426
Reputation: 1489
I finally found out here is the steps to follow here : https://juristr.com/blog/2018/01/ng-app-runtime-config/#runtime-configuration
1. create a service
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. Import this service in the app.module + create a initializer function **
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 { }
In my app.component :
constructor(private appConfig: AppConfigService) {
}
ngOnInit(): void {
this.myConfig = this.appConfig.getConfig();
}
Now i can display the config data in the template or anywhere in the application. When building, the json file is also exported and we can access it !
Upvotes: 2