首页 > 解决方案 > 由于 ngOninit 在角度 5 中显示未定义的对象数组

问题描述

即使我试图像这样访问 html 内部,它也没有提供任何价值

  <mat-nav-list>
      <a mat-list-item href="" *ngFor="let link of products"> {{ link.name }} </a>
   </mat-nav-list>

这是我的 JSON

[{"id":215,"name":"Book ambulance","slug":"book-ambulance","permalink":"http://staging.drmedapp.com.cp-36.webhostbox.net/demo/product/book-ambulance/","date_created":"2018-02-24T08:31:01","date_modified":"2018-02-24T08:32:13","type":"simple","status":"publish","featured":false,"catalog_visibility":"visible","description":"","short_description":"","sku":"","price":"0","regular_price":"0","sale_price":"","date_on_sale_from":"","date_on_sale_to":"","price_html":"<span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">&#8377;</span>0.00</span>","on_sale":false,"purchasable":true,"total_sales":0,"virtual":false,"downloadable":false,"downloads":[],"download_limit":-1,"download_expiry":-1,"download_type":"standard","external_url":"","button_text":"","tax_status":"taxable","tax_class":"","manage_stock":false,"stock_quantity":null,"in_stock":true,"backorders":"no","backorders_allowed":false,"backordered":false,"sold_individually":false,"weight":"","dimen

这是我的 .ts 文件,我更新了代码但仍然收到错误 this.products is not defined。

import { Component, OnInit } from '@angular/core';
import {Headers, Http, RequestOptions, URLSearchParams} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import * as WC from 'woocommerce-api';
import { WooApiService } from 'ng2woo';
import * as CryptoJS from 'crypto-js';

@Component({
  selector: 'app-pcat',
  templateUrl: './pcat.component.html',
  styleUrls: ['./pcat.component.scss']
})
export class PcatComponent implements OnInit {
  WooCommerce: any;
  public products: any;
  data: any;
  public crypto: any;
  typesOfShoes = ['Boots', 'Clogs', 'Loafers', 'Moccasins', 'Sneakers'];

  constructor(private woo: WooApiService) {}

  public getALL(){
    this.woo.fetchItems('products')
      .then(products => {
         for(var i = 0; i < products.length; i++) {
            this.products.push(products[i])
         }
      })
      .catch(error => console.log(error));
    } 
  ngOnInit(): void  {
    this.getALL();
  }
}

标签: javascriptarraysangularobjectangular5

解决方案


我认为你的问题是你没有将getAll()函数的返回值分配给你的products数组。

    public getALL(){
         this.woo.fetchItems('products')
           .then(products => {
              for(var i = 0; i < products.length; i++) {
                 this.products.push(products[i])
              }
           })
           .catch(error => console.log(error));
    } 

推荐阅读