问题描述
我需要在应用程序引导之前从服务器获取配置.我可以在主要ngModule的提供程序中使用此功能:
I need to get configuration from server before the application bootstraps. I was able to do that using this in providers in my main ngModule:
{
provide: APP_INITIALIZER,
useFactory: (links: Links) => () => links.init(),
deps: [Links, Http],
multi: true
}
链接服务:
init(): Promise<any> {
var observable = this.http.get('someUrl').map(res => res.json());
observable.subscribe(res => {
this.config = res;
});
return observable.toPromise();
}
此代码在应用程序引导之前执行,但是直到我的应用程序请求Links.config后,服务器的响应才会出现.在Promise解决之后,我如何强制应用程序不进行引导?我尝试了promise.resolve(),但没有帮助.
This code gets executed before the application bootstraps, but the response from server is not present until after my app asks for Links.config. How do I force the app to not bootstrap until after the Promise gets resolved? I tried promise.resolve(), but it didn't help.
我使用提供程序的方式我以为我强迫应用程序使用相同的Links实例,而且我认为数据已经在那儿了.请问我做错了什么?
The way I used providers I thought I forced the app to use the same instance of Links and also I thought the data would be already present there. What am I doing wrong please?
推荐答案
在我的代码中,我所做的工作完全相同,唯一的区别是,我在映射之前将请求转换为Promise.
In my code I am doing exactly same and it's working only difference is that I am converting the request to Promise before mapping.
public load(): Promise<void> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let url = this.urls.settings;
return this.http.get(url, { headers }).toPromise().
then(configs => {
this.startupSettings = configs.json();
}).catch(err => {
log(err);
});
}
......................
...............................
{
provide: APP_INITIALIZER,
useFactory: (config: StartupConfigurationService) => () => config.load(),
deps: [StartupConfigurationService],
multi: true
}
我不确定这是否有道理,但尝试可能会解决
I don't sure it will make sense but try may be it will solve
这篇关于Angular 2在引导之前从服务器获取配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!