Angular2 APP_INITIALIZER嵌套了http请求

Tom*_*myF 2 angular-cli angular

我一直在尝试APP_INITIALIZER在引导过程中使用加载一些配置数据(类似于如何将从后端渲染的参数传递给angular2引导程序方法,Angular2 APP_INITIALIZER不一致,以及其他).

我面临的问题是我需要发出2个请求,第一个请求到URL所在的本地json文件,然后请求该URL获取实际配置.

出于某种原因,启动不会延迟,直到承诺结算.

这是通过的方法调用的加载方法 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;
}
Run Code Online (Sandbox Code Playgroud)

这是一个完整的plnkr演示问题(检查控制台输出).

显然,我错过了对这个概念的重要理解.

如何让应用程序在加载组件之前等待两个请求都返回?

yur*_*zui 6

1)回报承诺

export function init(config: ConfigService) {
  return () => config.load();
}
Run Code Online (Sandbox Code Playgroud)

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;
        });
}
Run Code Online (Sandbox Code Playgroud)

Plunker示例

或者与我们的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();
          });
      });
  });
}
Run Code Online (Sandbox Code Playgroud)

Plunker示例