Displaying data issue with Typescript typed array

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.

Answer №1

**Efficient code for various scenarios**

//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: 'tomato',
        id: 1,
        measurment: 'slice'
      },
      {
        name: 'avocado',
        id: 2,
        measurment: 'piece'
      }];
    /*
      ingredients = [
        new Ingredient('tomato', 1, 'slice'),
        new Ingredient('avocado', 2, 'piece')
      ];
    */

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

Answer №2

If you want to make some changes in your Ingredient class, here is what you can do:

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 = 0;
   public measurement: string = 'none';
}

When setting the data inside your component, follow this example:

 private ingredientsList = [
    new Ingredient({
     name: 'spinach',
     amount: 2, 
     measurement: 'cups'
    })
  ];
console.log(ingredientsList);

I hope these suggestions are useful for you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm looking for a way to send a value to my component when the onBlur event is triggered on a PrimeNG autocomplete textbox. Any

I'm currently utilizing the PrimeNG autocomplete textbox. How can I pass a value to my component on the onBlur event? Template <p-autoComplete (ngModelChange)="orguser.userid = $target.value" class="ui-autocomplete autocomplete" [suggestions]="r ...

Does the React memo function modify the component's prop type?

I've come across a strange issue where defining two components causes compilation errors when written separately but not when written in the same file. test3.tsx import React from "react"; type ValueType = number[] | string[] | number | st ...

class-validator: ensures the correct number of digits are present in numeric values

Seeking assistance on validating the number of digits for numeric values using class-validator. Specifically, I want my entity to only accept numbers with 6 digits for a certain property. For example: const user1 = new User(); user1.code = 123456 // should ...

The issue with Angular Material Dialog hiding certain elements

In my Node.js Angular project, I am trying to implement a confirm dialog which should be a simple task. Utilizing Material styling to speed up development process. However, upon running the project, the opened dialog appears to be empty: The structure of ...

Issue with launching Angular 6 project

I attempted the solution from this link, but unfortunately, it did not work for me. I have cloned a project from GitLab and am attempting to run it. First, take a look at the output of my ng version command: . The project is based on Angular 6 and is ava ...

Adding a stylesheet dynamically in Angular 2: A step-by-step guide

Is there a method to dynamically add a stylesheet URL or <style></style> in Angular2? For instance, if the variable isModalOpened is set to true, I want to apply certain CSS styles to elements outside of my root component, such as the body or ...

What is the best way to swap out the if else statement with a Ternary operator within a JavaScript function?

Is there a way to replace the if else statement in the function using a Ternary operator in JavaScript? private getProductName(productType: string): string { let productName = 'Product not found'; this.deal.packages.find(p => p.isSele ...

Preparing an Angular 2 application for deployment on a live IIS server

After following the Angular 2 tutorial successfully and getting everything to work as expected, I realized that it doesn't cover packaging for production distribution. Is there a standard method for creating a clean distribution package without includ ...

Building Interface/Type with Static Properties and Constructor Signature in TypeScript

I am looking to devise an interface or a type that contains static properties and a constructor signature. My goal is to utilize this interface/type as a parameter for a function. I experimented with using an interface, but encountered limitations in decla ...

Why won't Angular 4 create the node_modules folder when using ng new to initialize a new project?

Recently reinstalled Angular and began a new project using ng new. However, I encountered issues when trying to run ng serve after creating the project and changing into its directory. On my Mac Mini, I can simply navigate to the project folder and run ng ...

Differentiating AWS API errors in TypeScript: A guide

How can I write different handlers in TypeScript for ThrottlingException and ExecutionLimitExceeded when starting a StepFunction execution? new StepFunction.startExecution({}, (err, data) => { if (err) { // Need to identify ThrottlingExcepti ...

How to use TypeScript to set a value in ng2-ckeditor

I have implemented two ckeditor instances using *ngFor: <div class="form-group" *ngFor="let lang of languages"> <span>Legal text in {{lang.translate}} {{lang.abbr}}</span> <ckeditor id="{{lang.abbr}}" formControlName="{{lang.abbr} ...

Replace the default Material UI 5.0 typography theme with custom fonts on a global scale

My current challenge involves incorporating two personal fonts into the Material UI 5.0. My goal is to apply these fonts globally by overriding the theme settings. However, I have encountered issues with loading the fonts properly and modifying the typogra ...

What is the best way to combine an Angular project with an existing Node.js project?

I've successfully deployed my Angular project on Heroku and my Node.js API REST on Heroku as well. However, they are separate projects with different URLs but function together. Is there a way to combine them on the server and have just one URL? Curr ...

It is advisable for the subscriber not to halt upon encountering an error within the

Dealing with a problematic subscriber that automatically unsubscribes itself when an error occurs: observable .subscribe( (data) => { // logic encountering an error // similar to throw new Error() } ) To avoid this, I can use t ...

Tips for successfully clearing the localStorage in an Ionic2 application upon exiting

Could someone please provide guidance on how to detect when the application is being exited using the hardware back button and then clear my localStorage data? I have three main reasons for needing this functionality: 1. Prompt the user to confirm if they ...

I'm curious if someone can provide an explanation for `<->` in TypeScript

Just getting started with TypeScript. Can someone explain the meaning of this symbol <->? And, is ProductList actually a function in the code below? export const ProductList: React.FC<-> = ({ displayLoader, hasNextPage, notFound, on ...

The Error message "Property 'data' is not present in Type <void> | AxiosHttpResponse<any>" is indicating that the data property is missing on

When I fetch data for a specific user, I have a promise that I use to setState. Below is the implementation: getUserUsername = (): string => { const { match } = this.props; return match.params.username; }; onFetchUser = () => getUse ...

Choose the currently active md-tab within the md-dialog's md-tab-group

I need to create a dynamic md-dialog with an md-tab-group that has two tabs. The md-dialog should open based on the button clicked, displaying the corresponding tab content. The initial template where the md-dialog is triggered: <button md-button class ...

Updating a label dynamically in Angular

QUESTION: Is there a way to dynamically change the text of a label based on a certain condition? Specifically, I want the label to be blank when I'm on a specific route in my App. CURRENT APPROACH: <RadSideDrawer allowEdgeSwipe=&quo ...