Angular2 APP_INITIALIZER 嵌套 http 请求

标签 angular angular-cli

我一直在尝试在引导过程中使用 APP_INITIALIZER 来加载一些配置数据(类似于 How to pass parameters rendered from backend to angular2 bootstrap methodAngular2 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/

相关文章:

angular - Typescript - 类型 'false' 不可分配给类型 'true'

node.js - 从 Angular 11 升级到 12 导致对等依赖冲突

Angular 6 CLI -> 如何制作 ng build build project + libraries

Angular-cli serve watch 在 vagrant windows 主机下不工作

node.js - 即使 @angular/cli 是全局的并且位于环境变量中,也找不到 ng

angular - Azure 事件目录注销

javascript - 按类型过滤数组对象并将键值与对象进行比较

html - 如何调整复选框周围的点击区域?

angular - 如何避免使用 View 中的方法触发组件中的更改检测?

angular - 我不想在重新加载页面 Angular 4 后注销