我有Ionic2
个应用SideMenu
模板,rootPage
我有这个代码
export class HomePage {
products: any = [];
constructor(public navCtrl: NavController, public navParams: NavParams, private woo: WooCommerce) {
}
ionViewDidLoad() {
this.woo.Fetch('products', function (res) {
this.products = res.products;
//console.log(this.products[0]);
}.bind(this));
}
ngOnInit() {
}
}
其中WooCommerce
是WooCommerce-Nodejs
export class WooCommerce {
woo: any = null;
constructor(public http: Http, private util: Utilities) {
this.woo = WooCommerceAPI();
}
Fetch(what, callback) {
return this.woo.getAsync(what).then(function (result) {
callback(JSON.parse(result.body));
});
}
}
在page.ts
ionViewDidLoad() {
this.woo.Fetch('products', function (res) {
this.products = res.products;
console.log(this.products);
}.bind(this));
}
和page.html
<ion-col center text-center col-6 *ngFor="let product of products">
<ion-card>
<img src="{{product.featured_src}}" />
<ion-card-content>
<ion-card-title style="font-size: 100%">
{{ product.title | StripHTML }}
</ion-card-title>
</ion-card-content>
<ion-row center text-center>
<p style="color: red">
{{ product.price_html | StripHTML:{split:" ",index:0} }}
</p>
</ion-row>
</ion-card>
</ion-col>
问题:Fetch
确实加载并返回数据,但页面视图没有刷新,直到我点击菜单切换按钮,然后页面重新渲染或刷新,产品/数据显示...
Fetch
调用callback
函数重新渲染或刷新时,是否可以使用它?
答案 0 :(得分:1)
Angular通常会检测更改并更新其视图。它可能无法在 Woocommerce API中获得更新。
尝试使用ngZone
确保Angular检测到更改。
import {NgZone} from '@angular/core'
constructor(ngZone: NgZone){}//inject in constructor
ionViewDidLoad() {
this.woo.Fetch('products', function (res) {
this.ngZone.run(()=>{//use here
this.products = res.products;
console.log(this.products);
});
}.bind(this));
}