0
method.then()
內AppComponent在method.then響應()不會被調用下面scenario-如何等待在angular2
這是我的加載方法在服務 -
load(): Promise<IAppSettings> {
return this.http.get('api/AppSettingsApi')
.toPromise()
.then((response: Response) => {
this._appSettings = response;
console.log('this._appSettings: ' + JSON.stringify(this._appSettings));
return this._appSettings;
})
.catch((error) => Promise.reject(error.message || error));
從上面塊,我可以看到 console.log('this._appSettings: ' + JSON.stringify(this._appSettings));
正確的輸出從AppComponent這種服務怎麼樣,我呼籲負荷方法constructor-
constructor(
private router: Router,
private route: ActivatedRoute,
private customerService: CustomerService,
private appSettings: AppSettingsService,
) {
this.appSettings.load()
.then((data) => {
console.log('config loaded successfully');
console.log('========================================================================');
this.envName = data.environmentSettings.envName;
console.log('this.envName: ' + this.envName);
console.log('========================================================================');
})
.catch(() => { console.error('Error occurred while loading config'); });
但我的then()
部分永遠不會被調用。我在瀏覽器控制檯中看不到任何錯誤。
我想在我的AppComponent方法中等待響應,請你指導我這個嗎?
嘗試添加'。在.toPromise()之前的first()'就像'return this.http.get(...)。first()。toPromise()。then(...)''。 ('first'需要像'toPromise'一樣導入。 –
您是否嘗試過使用Observable而不是Promise?使用Observable應該更加一致,即使您只是訂閱,您也不必將其轉換爲承諾並且可以節省您一些電話 – Supamiu
感謝Gunter - 第一()工作 – 439