Typescript类型数组不显示数据

时间:2019-04-29 03:42:02

标签: angular typescript typed-arrays

我正在使用Angular 7和Typescript 3在将在组件中使用的服务中创建填充前的成分数组,但是当我将其打印到控制台时,我得到的是一个空对象数组。

如果我使用对象文字创建类型化的数组,它将起作用,但是如果我使用new运算符创建该数组,则该数组将不包含任何数据。

编辑:添加了成分分类的片段

export class Ingredient {
    constructor(name?: string, amount?: number, measurement?: string) {}
}

其中包含数据:

export class ShoppingListService {
  private ingredients: Ingredient[] = [{
    name: 'shrimp',
    amount: 1,
    measurement: 'cup'
  },
  {
    name: 'bib lettuce',
    amount: 1,
    measurement: 'bunch'
  }];
  constructor() { 
   console.log('ingredients', this.ingredients);
   }

控制台输出:

ingredients [{name: "shrimp", amount: 1, measurement: "cup"},
             {name: "bib lettuce", amount: 1, measurement: "bunch"}
            ]

这不包含数据

export class ShoppingListService {
  private ingredients = [
    new Ingredient('shrimp', 1, 'cup'),
    new Ingredient('bib lettuce', 1, 'bunch')
  ];

  constructor() {
    console.log('ingredients', this.ingredients);
   }
}

控制台输出:

ingredients [Ingredient{}, Ingredient{}]

我也尝试使用以下语法,但得到的输出与上面的示例相同:

private ingredients: Ingredient[] = [
    new Ingredient('shrimp', 1, 'cup'),
    new Ingredient('bib lettuce', 1, 'bunch')
  ];

我这里缺少一些打字稿或角度逻辑吗?上面的示例在此处的Angular文档中使用: Angular: Using the Hero class

2 个答案:

答案 0 :(得分:0)

所以我认为您需要在“成分”类中进行这些更改

 private ingredients = [
    new Ingredient({
     name: 'bib lettuce',
     amount: 1, 
     measurement: 'bunch'
    })
  ];

在组件内部用于设置数据

console.log(ingredients);
in-app-messaging

我希望它可以帮助您

答案 1 :(得分:0)

**Working code for both scenario** 


//ingredient.ts

export class Ingredient{
  constructor(public  name: string, public id: number, public measurment: string){
  }  
}

//ingredient.component.ts

    import {Component} from '@angular/core';
    import { Ingredient } from './ingredient ';
    @Component({
      selector: 'app-ingredient',
      template: 'Ingredient'
    })
    export class IngredientComponent{
        private ingredients: Ingredient[] = [{
        name: 'shrimp',
        id: 1,
        measurment: 'cup'
      },
      {
        name: 'bib lettuce',
        id: 1,
        measurment: 'bunch'
      }];
    /*
      ingredients = [
        new Ingredient('shrimp', 1, 'cup'),
        new Ingredient('bib lettuce', 1, 'bunch')
      ];
    */

      constructor(){
    console.log(this.ingredients);
      }
    }