2017-11-11 63 views
0

我正在學習離子2,目前正面臨一些離子生命週期問題。 我想在api獲取成功數據後顯示數據。離子2呈現數據之前查看加載

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()**數據正確,但越來越沒有反映我的觀點/ 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的調用,並得到響應,但不能看到我的視圖頁上這個結果,現在如果我點擊任何其他選項卡,然後再次點擊類別選項卡,然後我可以看到這些數據。

由於我是新來的離子2我無法解決這個問題。 任何人都可以幫我解決這個問題。

感謝提前:)

回答

0

包裝你的手風琴,其中包括關於您的信息數據的條件一個div:

<div *ngIf="information.length>0;else noData"> 
    <accordion *ngFor="let catParent of information" [title]="catParent.items.name"> 
      ... 
    </accordion> 
</div> 

<ng-template #noData>Loading accordion...</ng-template> 
1
  1. 這火從服務或服務提供者類的HTTP請求的最佳實踐
  2. IonViewDidLoad僅在加載頁面時運行,以便在HTTP請求被觸發之前加載空白頁面。
  3. 使用IonViewCanEnter可以認爲之前運行呈現使用ionic loading component這樣用戶就會知道什麼
  4. 顯示加載在後臺發生