异步调用返回后重新加载页面内容

时间:2017-04-05 10:28:03

标签: javascript node.js angular ionic-framework ionic2

我有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() {
  }

}

其中WooCommerceWooCommerce-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函数重新渲染或刷新时,是否可以使用它?

1 个答案:

答案 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));
      }