Search code examples
angulartypescripttyped-arrays

Typescript typed array not displaying data


I am using Angular 7 and Typescript 3 to create a pre-populate array of ingredients in a service that will be used in a component but when I print the array out to the console, I am getting an array of empty objects.

If I create the typed array using object literals it will work, but if I create the array using the new operator, the array, will not contain any data.

EDITED: Added snippet of ingredient class

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

This contains data:

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

console output:

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

This this doesn't contain data

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

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

console output:

ingredients [Ingredient{}, Ingredient{}]

I have also tried using the following syntax, but I get the same output as the example above:

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

is there some typescript or angular logic that I am missing here? The example above is used in the Angular docs here: Angular: Using the Hero class


Solution

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