无法在Ionic中获得数组的正确索引

时间:2019-01-04 09:21:14

标签: html angular api ionic-framework ionic3

我正在从Laravel制造的API中获取产品类别,但是当我在HTML中获取类别时,它显示错误,但在控制台中,它显示类别值。

这是我的服务: restapi.ts

apiUrl3 = 'http://beegoodhoney.in/HoneyApi/category';

getproductcategories()
  {
    return new Promise(resolve => {

      var headers = new HttpHeaders();
      headers.append('Access-Control-Allow-Origin' , '*');
      headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
      headers.append('Accept','application/json');
      headers.append('content-type','application/json');

    this.http.get(this.apiUrl3, {headers: headers}).subscribe(data => {
      resolve(data);},
    err => {
    console.log(err);
    });
    });
}

此软件运行良好,我正在产品页面中使用此服务来获取产品类别。

这是我的 product.ts

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { RestapiProvider } from '../../providers/restapi/restapi';
import { ProductdetailsPage } from './../productdetails/productdetails';
import { CartPage } from './../cart/cart';

@IonicPage()
@Component({
  selector: 'page-product',
  templateUrl: 'product.html',
})
export class ProductPage {
  users: any;
  categories: any;
  constructor(public navCtrl: NavController, public navParams: NavParams, public restProvider: RestapiProvider) {
  this.getcategories();
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad ProductPage');
  }

  getcategories()
  {
    this.restProvider.getproductcategories()
      .then(data => {
      this.categories = data;
      console.log(this.categories);
      });
  }
}

当我在控制台中打印值时,它显示响应,但是在HTML中,它显示错误。

这是我的p roduct.html

<h4 class="mynewph22">{{categories.msg?.cat[0].category_name}}</h4>

错误:无法读取未定义的属性“ cat”

在控制台中响应:

{status: "success", msg: {…}}
msg:
cat: Array(4)
0: {id: "1", main_cat_id: "1", category_name: "Dark Honey", category_img: "http://beegoodhoney.in/uploads/categoriesdark-honey11.jpg", cat_desc: "testinggg"}
1: {id: "2", main_cat_id: "1", category_name: "Eucalyptus honey", category_img: "http://beegoodhoney.in/uploads/categorieseucalyptus-honey1.jpg", cat_desc: "testinggg"}
2: {id: "3", main_cat_id: "1", category_name: "Light Forest Honey", category_img: "http://beegoodhoney.in/uploads/categorieslight-honey3.jpg", cat_desc: "sssss"}
3: {id: "4", main_cat_id: "1", category_name: "Organic Honey", category_img: "http://beegoodhoney.in/uploads/categoriesorganic-honey2.jpg", cat_desc: null}
length: 4

问题是,当我在HTML中打印产品类别时,它显示错误。非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

这很有意义,因为您的html试图达到一个尚未准备好的值。 由于您使用的是Promise而不是可观察的,因此您需要通过类似这样的类别来限制html的条件:

<h4 class="mynewph22" *ngIf="categories && categories.msg && categories.msg.cat && categories.msg.cat.length">{{categories.msg.cat[0].category_name}}</h4>

当对象变为可用并显示数据时,Angular将触发更改检测。