While working with Angular 7 and Typescript 3, I encountered an issue where I was trying to pre-populate an array of ingredients in a service for use in a component. However, when I checked the console output, the array was showing empty objects.
If I initialized the array using object literals, it worked fine. But when I used the new operator to create the array, it did not contain any data.
I even added a snippet of the Ingredient class:
export class Ingredient {
constructor(name?: string, amount?: number, measurement?: string) {}
}
Here's an example that 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"}
]
And here's an example without 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 also tried a different syntax but ended up with the same result as above:
private ingredients: Ingredient[] = [
new Ingredient('shrimp', 1, 'cup'),
new Ingredient('bib lettuce', 1, 'bunch')
];
I'm wondering if there might be some TypeScript or Angular logic that I may have overlooked. The example mentioned is from the Angular docs found here.