I am loading config data from asp.net web api using http at the startup using APP_initializer .I am inspired by this stackoverflow thread Angular2 load configuration from backend on startup and this
My app.module.ts
providers: [
HttpClient,
{
provide: APP_INITIALIZER,
useFactory: (appConfigSvc:AppConfigService) => () => {
appConfigSvc.load();
},
deps: [AppConfigService],
multi: true
}, AppConfigService
The appConfig.Service.ts
@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);
}
Then use it in any component like this:
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
}
}
The issue is, I am not able to access the config data in ngOninit of any components. But it is accessible inside button click event handler or similar methods which usually gets called a while after the application started.
Appreciate any help. Thanks.