2017-05-04 108 views
2

我一直试图在引导过程中使用APP_INITIALIZER加载一些配置数据(类似于How to pass parameters rendered from backend to angular2 bootstrap method,Angular2 APP_INITIALIZER not consistent和其他)。Angular2 APP_INITIALIZER嵌套的http请求

我面临的问题是我需要做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证明了问题(检查控制台输出)。

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

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

回答

5

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

+0

'switchMap()'是我缺少的链接,非常感谢! – TommyF

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(); 
    } 
} 
+0

你是正确的,这是回回在以前的尝试中,我忘了将它改回来,感谢您的支持! – TommyF