本文介绍了Angular2 APP_INITIALIZER嵌套的HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在引导过程中尝试使用APP_INITIALIZER来加载一些配置数据(类似于,等).

I've been trying to use the APP_INITIALIZER during the bootstrap process to load some configuration data (similar to How to pass parameters rendered from backend to angular2 bootstrap method, Angular2 APP_INITIALIZER not consistent, and others).

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

The problem I'm facing is that I need to make 2 requests, the first one to a local json file where a URL resides, then the request to that URL to get the actual configuration.

但是由于某种原因,启动没有被延迟,直到承诺解决为止.

For some reason however the startup is not delayed until the promise resolves.

这是通过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 演示了问题(检查控制台输出).

And here is a complete plnkr demonstrating the problem (check the console output).

很明显,我缺少对该概念的重要理解.

Obviously I'm missing an important understanding of the concept.

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

How can I get the app to wait for both requests to return before the component is loaded?

推荐答案

1)返回承诺

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请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:04