在角度5中显示undefined duing ngOninit的对象数组

时间:2018-05-29 01:17:59

标签: javascript arrays angular object angular5

即使我试图像这样访问内部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文件,我更新了代码,但仍然收到错误。没有定义产品。

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();
  }
}

3 个答案:

答案 0 :(得分:1)

我认为您的问题是您没有将:get_substring SETLOCAL ENABLEDELAYEDEXPANSION SET "string=!%~1!" SET "substringLength=!%2!" SET "substring=!string:~0,%substringLength%!" SET "string=!string:~%substringLength%!" IF "%string:~0,1%"==" " SET "string=%string:~1%" ENDLOCAL & SET "%1=%string%" & SET "%3=%substring%" EXIT /B 0 函数的返回值分配给getAll()数组。

products

答案 1 :(得分:0)

您需要将products属性填充到当前回复

public getALL(){
    this.woo.fetchItems('products')
    .then(products => { this.products = products; })
    .catch(error => console.log(error));
} 

答案 2 :(得分:0)

在进行API调用时,看起来产品是动态加载的。在API调用完成之前,属性产品将持有滴灌值undefined,如下所示。

public products: any;

在产品加载之前,模板不知道这是一个数组,也就是模板失败的地方。现在修复用空数组初始化属性。

public products: any[] = [];

简而言之,看起来这是初始化的问题。

希望这有帮助