打字稿类型数组不显示数据

Typescript typed array not displaying data

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

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

已编辑:添加了成分片段 class

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 文档中使用: Angular: Using the Hero class

所以我认为您需要对成分进行这些更改 class

export class Ingredient {
   constructor(data?: any) {
     this.name = data.name;
     this.amount = data.amount;
     this.measurement = data.measurement;
   }
   public name: string = null;
   public amount: number = null;
   public measurement: string = null;
}

并在您的组件内部设置数据

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

希望对你有所帮助

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