I need to make two HTTP call one after another before angular initialize. Is there any way to initialize angular 2 synchronously?
Please do not say our app should work asynchronously. I am working on generic build using "angular-cli" . First i need to fetch the environment which is set in a json file and on the basis of that environment i need to load configuration. So i need two HTTP calls.
{
provide: APP_INITIALIZER,
useFactory: (config: AppConfig) => () => config.load(),
deps: [AppConfig], multi: true
}
Inside load() i have two http call one inside other but before two call get completed angular is initialized.
You're on a correct way. You can make both http calls into config.load() function.
public load() {
return new Promise((resolve, reject) => {
this.http.get('first.json').map( res => res.json() ).catch((error: any):any => {
console.error('Error at first call');
resolve(error);
return Observable.throw(error.json().error || 'Server error');
}).subscribe( (firstResponse) => {
let request = this.http.get('second.json');
request
.map( res => res.json() )
.catch((error: any) => {
console.error('Error at second call');
resolve(error);
return Observable.throw(error.json().error || 'Server error');
})
.subscribe((secondResponse) => {
//Here i have both
firstResponse, secondResponse
resolve(true);
});
});
});
}
Consider the fact that functions and lambdas are not supported to useFactory anymore, so you have to rewrite it little bit. Also make sure that you provide your AppConfig
function initialConfigLoad(config: AppConfig) {
return () => config.load();
};
providers: [
...
AppConfig, // <- Provide AppConfig
{
provide: APP_INITIALIZER,
useFactory: initialConfigLoad,
deps: [AppConfig],
multi: true
}
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With