私はhome.tsにservice.tsを呼び出して、Storageからアイテムをロードしています。Ionic 2 PromiseのアイテムをngOnInitにロード
export class HomePage {
products;
ionViewDidEnter() {
this.products = this.productService.products;
}
ngOnInit(){
this.productService.fetchProducts();
this.products = this.productService.products;
}
}
export class ProductService{
products;
fetchProducts(){
this.storage.get('products') // returns a promise which returns data or error
.then(
(products) => {
// assign to this.expenses only if not null. When first //strt, can be null. If null, assign empty array []
products? this.products = products : this.products = [];
console.log("fetch Products:" + this.products);
return this.products;
})
.catch(
err => console.log(err)
);
}
次に、項目をhome.html
にレンダリングします。 問題は、アプリが起動して初めてアイテムが表示されないことです。しかし、別の画面に移動してhome.tsに戻ると、項目は正常に表示されます。私はこれがionViewDidEnterであることを理解しています。おそらく最初の回では、fetchProductsの約束事は非同期です。しかし、どのように最初のラウンドで商品をngOnInit
に登録するのですか?
可能な複製の[非同期呼び出しからの応答を返すにはどうすればいいですか?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – echonax
ありがとうございました。しかし、私の場合、特定のコードはどうなりますか? – Jason