I've been trying to deploy on DevOps an Angular 8 application and use configuration inside .json files in order to not re-build the entire application for different environments.
I used these 2 posts in order to create all the configurations:
Continuously Deploying Angular to Azure App Service with Azure DevOps
and a Stack overflow answer:
App.settings - the Angular way?
Note that I'm not interested on using the environment.ts
way, as this way will require me to re-build the solution for each environment.
So, I prepared all my code like this:
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [
{
provide: APP_INITIALIZER,
useFactory: (appConfigService: ConfigService) => {
return () => {
//Make sure to return a promise!
return appConfigService.loadAppConfig();
};
},
deps: [ConfigService],
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule {}
My ConfigService.ts
:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ConfigService {
private appConfig: any;
constructor(private http: HttpClient) {}
loadAppConfig() {
return this.http.get('./assets/appconfig.json')
.toPromise()
.then(config => {
this.appConfig = config;
});
}
get apiBaseUrl() {
if (!this.appConfig) {
throw Error('Config file not loaded!');
}
return this.appConfig.apiUrl;
}
}
And then, the main object that needs to load appconfig.json information:
export class ApiService {
apiUrl: string;
constructor(private readonly httpClient: HttpClient,
private configService: ConfigService) {
this.apiUrl = this.configService.apiBaseUrl;
}
ngOnInit() {
this.apiUrl = this.configService.apiBaseUrl;
}
}
But then, while loading the app, this message arises:
If I debug the app, the appsettings.json
file is loading info, but then it looks like the angular init is happening before loading the appsettings.
What I'm doing wrong?