Angular2 APP_INITIALIZER 嵌套的 http 请求 [英] Angular2 APP_INITIALIZER nested http requests

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

问题描述

我一直在尝试在引导过程中使用 APP_INITIALIZER 来加载一些配置数据(类似于 如何将后端渲染的参数传递给angular2 bootstrap方法, Angular2 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) Return promise

1) Return 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 示例

或使用我们的 rxjs 运算符

or withour rxjs operator

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 示例

这篇关于Angular2 APP_INITIALIZER 嵌套的 http 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆