Implementing a method to load configuration data from an ASP.NET web API using HTTP at startup via APP_INITIALIZER. This approach was influenced by a discussion on Stack Overflow about loading configuration in Angular2 here and here.
Snippet from app.module.ts:
providers: [
HttpClient,
{
provide: APP_INITIALIZER,
useFactory: (appConfigSvc:AppConfigService) => () => {
appConfigSvc.load();
},
deps: [AppConfigService],
multi: true
}, AppConfigService
The appConfig.Service.ts code snippet:
@Injectable()
export class AppConfigService {
private serviceApiUrl = "api/AppConfigApi/";
public applicationConfig: Appconfigmodel.IAppConfigModel;
constructor(private _http: Http) {
}
getApiConfig(): Appconfigmodel.IAppConfigModel {
return this.applicationConfig;
}
load() { this.getApplicationConfig(); }
getApplicationConfig(): Observable<Appconfigmodel.IAppConfigModel> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({
headers: headers
});
//pulling config data from web.config of a ASP.Net Web API2
return this._http.get(this.serviceApiUrl + 'GetApplicationConfig', options)
.map((response: Response) => <Appconfigmodel.IAppConfigModel>response.json())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}
Usage in components:
export class FirstComponent {
constructor(private _appConfigService: AppConfigService) {
}
ngOnInit() {
this.applicationConfig= this._appConfigService.getApiConfig(); // The config dat is getting as undefined
}
//button click
clickButton()
{
this.applicationConfig= this._appConfigService.getApiConfig(); // The config data is populated here
}
}
Encountering difficulty in accessing the config data in ngOninit of components, but accessible in button click event handler or similar delayed methods.
Any assistance is appreciated. Thank you.