javascript – 离子2在视图加载之前渲染数据
作者:互联网
我正在学习离子2并且目前面临一些离子生命周期问题.
我希望在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);
});
}
}
我试图用带有** ngOnInit()&的构造函数()来调用api. ionViewDidLoad()**数据正常但未反映在我的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正在调用并获得响应,但无法在我的视图页面上看到此结果,现在,如果我单击任何其他选项卡并再次单击类别选项卡,则我能够看到此数据.
由于我是离子2的新手,我无法解决这个问题.
任何人都可以帮我解决这个问题.
提前致谢 :)
解决方法:
>最佳做法是从服务或提供程序类触发HTTP请求
> IonViewDidLoad仅在加载页面时运行,因此在触发HTTP请求之前将加载空页面.
>使用可在视图渲染之前运行的IonViewCanEnter
>使用ionic loading component显示加载,以便用户知道后台正在发生的事情
标签:javascript,jquery,angular,ionic2,ionic-view 来源: https://codeday.me/bug/20190828/1749681.html