【问题标题】:Angular2 APP_INITIALIZER nested http requestsAngular2 APP_INITIALIZER 嵌套的http请求
【发布时间】:2017-05-04 12:52:55
【问题描述】:

我一直在尝试在引导过程中使用APP_INITIALIZER 来加载一些配置数据(类似于How to pass parameters rendered from backend to angular2 bootstrap methodAngular2 APP_INITIALIZER not consistent 等)。

我面临的问题是我需要发出 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;
}

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

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

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

【问题讨论】:

    标签: angular angular-cli


    【解决方案1】:

    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

    【讨论】:

    • switchMap() 是我缺少的链接,非常感谢!
    【解决方案2】:

    您没有在提供的 plunkr 中返回任何承诺:

    export function init(config: ConfigService) {
      return () => {
        config.load();
      };
    }
    

    实际上应该是:

    export function init(config: ConfigService) {
      return () => config.load();
    }
    

    export function init(config: ConfigService) {
      return () => {
        return config.load();
      }
    }
    

    【讨论】:

    • 你是对的,这是之前的尝试,我忘记改回来了,谢谢你!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多