我一直在尝试在引导过程中使用 APP_INITIALIZER
来加载一些配置数据(类似于 How to pass parameters rendered from backend to angular2 bootstrap method 、 Angular2 APP_INITIALIZER not consistent 等)。
我面临的问题是我需要发出 2 个请求,第一个请求指向 URL 所在的本地 json 文件,然后请求该 URL 以获取实际配置。
但是由于某种原因,启动不会延迟到 promise 兑现为止。
这是通过APP_INITIALIZER
调用的加载方法
public load(): Promise<any>
{
console.log('bootstrap loading called');
const promise = this.http.get('./src/config.json').map((res) => res.json()).toPromise();
promise.then(config => {
let url = config['URL'];
console.log("loading external config from: ./src/" + url);
this.http.get('./src/' + url).map(r => r.json()).subscribe(r => { this.config = r; console.dir(r);});
});
return promise;
}
这是完整的plnkr演示问题(检查控制台输出)。
显然我缺少对这个概念的重要理解。
如何让应用程序在加载组件之前等待两个请求返回?
最佳答案
1)返回 promise
export function init(config: ConfigService) {
return () => config.load();
}
2)保持秩序
public load(): Promise<any> {
return this.http.get('./src/config.json')
.map((res) => res.json())
.switchMap(config => {
return this.http.get('./src/' + config['URL']).map(r => r.json());
}).toPromise().then((r) => {
this.config = r;
});
}
<强> Plunker Example
或者不使用我们的 rxjs 运算符
public load(): Promise<any> {
return new Promise(resolve => {
const promise = this.http.get('./src/config.json').map((res) => res.json())
.subscribe(config => {
let url = config['URL'];
this.http.get('./src/' + url).map(r => r.json())
.subscribe(r => {
this.config = r;
resolve();
});
});
});
}
<强> Plunker Example
关于Angular2 APP_INITIALIZER 嵌套 http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43783437/