我正在学习ionic 2,目前面临一些 ionic 生命周期问题。
我想在api获取成功数据后显示数据。

import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import {LoadingController} from 'ionic-angular';

import WooCommerceAPI from 'woocommerce-api';

@Component({
  selector: 'page-category',
  templateUrl: 'category.html',
})
export class CategoryPage {

  information: any[] = [];
  infoChild: any[] = [];
  wooApi: any;
  wooCat: any;
  categories: any = [];

  constructor(public navCtrl: NavController, public loadingCtrl: LoadingController) {
      this.wooApi = WooCommerceAPI(
          {
            url: 'abc.com/api/v1/cat',

          }
        );
//here also tried to call api

    }


  ngOnInit() {
//here also tried to call api

  }
  ionViewDidLoad() {
    console.log("calling api");
    /*from with nginit*/
    this.wooApi.getAsync('products/categories?parent=0').then((data) => {
      console.log("success");
      this.wooCat = JSON.parse(data.body);
      //this.information = this.wooCat;
      for (let i = 0; i < this.wooCat.length; i++) {
        console.log("in for loop");
        this.wooApi.getAsync('products/categories?parent=' + this.wooCat[i].id).then((data) => {
          console.log("get success", i);
          let wooChild = JSON.parse(data.body);
          for (let x = 0; x < wooChild.length; x++) {
            this.infoChild.push(wooChild[x]['name']);
          }
          //console.log(this.infoChild)
          this.information.push({
            'items': {
              'name': this.wooCat[i]['name'],
              'children': [{
                'name': this.infoChild
              }]
            }
          });
          this.infoChild = [];
        });

      }
      console.log("current data", this.information);

    });

  }

}

我试图用构造函数()调用api,同时也使用** ngOnInit()和ionViewDidLoad()**数据正在正确显示,但未反射(reflect)在我的view/html页面上。

我的HTML代码如下:
<accordion *ngFor="let catParent of information" [title]="catParent.items.name">
      <!-- (click)="itemSelected(item)" -->
      <ion-list *ngFor="let catChild of catParent.items.children">
          <button ion-item *ngFor="let catChildName of catChild.name">
            {{ catChildName }}
          </button>
        </ion-list>
  </accordion>

因此,当我单击“类别”选项卡api正在调用并获得响应但无法在查看页面上看到此结果时,现在,如果我单击任何其他选项卡,然后再次单击“类别”选项卡,则可以看到此数据。

由于我是ionic 2的新手,因此无法解决此问题。
谁能帮我解决这个问题。

提前致谢 :)

最佳答案

  • 最佳实践是从服务或提供程序类
  • 触发HTTP请求
  • IonViewDidLoad仅在页面加载时运行,因此将在激发HTTP请求之前加载空页面。
  • 使用IonViewCanEnter,可以在 View 呈现
  • 之前运行
  • 使用ionic loading component显示加载,因此用户将知道
  • 后台正在发生某些事情

    10-04 22:04
    查看更多