2017-05-04 60 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