我試圖讓我的應用程序呈現數據,這是返回Promises的異步http請求的結果。我已經設置了我的代碼,以便它在ngOnInit
方法中執行,以便在視圖呈現之前處理所有邏輯。但是,我遇到了大多數Promise數據在渲染之前加載的問題,但是有些數據滯後(可能是由於多個HTTP請求),因此視圖的其餘部分已經呈現,然後該數據會彈出幾個幾秒鐘後。如何保持視圖模板的加載狀態,直到所有Promise數據都解決了? [Angular2,JavaScript]
Here is the full codebase on Github。
我對Angular2和ES6 Promises相當陌生,所以我仍然在玩Promise解析和發送回數據的方式,以便與我聯繫。
我的loadMore()
方法從ngOnInit
被調用來加載頁面時加載初始數據。這個問題(我認爲)的
loadMore() {
this.isLoading = true;
this.pokedexService.getPokemon(this.pokemon.length, 9)
.then(pokemon => {
pokemon = pokemon.map(p => {
p.imageLoaded = false;
this.pokedexService.getPokemonTypes(p.id)
.then(types => {
p.types = types;
});
return p;
});
this.pokemon = this.pokemon.concat(pokemon);
this.isLoading = false;
this.error = false;
})
.catch(() => {
this.error = true;
this.isLoading = false;
})
}
部分是對API的調用次數:getPokemon()
使得一個調用來檢索9個口袋妖怪API資源,然後getPokemonTypes()
使一個呼叫爲每個9個API資源。兩種方法都返回Promises - 但是,從getPokemon()
加載的數據正確加載到視圖中;它的口袋妖怪類型從每次調用加載到getPokemonTypes()
,在事實之後彈出到視圖中。下面是從pokedex.service.ts
邏輯兩種get
方法:
getPokemon(offset: number, limit: number): Promise<any> {
return this.http.get(`${this.baseUrl}?offset=${offset}&limit=${limit}`)
.toPromise()
.then(response => response.json().results)
.then(items => items.map((item, idx) => {
const id: number = idx + offset + 1;
return {
name: item.name,
sprite: `${this.baseSpriteUrl}${id}.png`,
id
};
}));
}
getPokemonTypes(id: number): Promise<any> {
return this.http.get(`${this.baseUrl}${id}/`)
.toPromise()
.then(response => response.json())
.then(details => {
const types = details.types
.map(t => {
return t.type.name;
});
return types;
});
什麼是對代碼進行優化,以使所有的數據負荷在一起,沒有渲染的數據創建一個數(5-7)第二延遲的最佳方式?
observables!角度是建立在他們周圍 - 他們比承諾靈活得多 - 檢查RxJS – danimal
我還是新來的es6功能和angular2 - 我讀了一些關於observables,但目前不知道如何使用它們在這種情況下實現它(否則this.http.get會返回一個Observable,但我已經使用.toPromise()將事物保持在Promise範例中,因爲它更適合我)。 –
你可以閱讀這篇文章,瞭解如何將promise鏈轉換爲observable鏈:https://medium.com/@juliapassynkova/q-map-to-rxjs-981936a2b22d –