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

Using the `window` object in Jasmine with Angular, a mock can be created for testing purposes

In my current project, I have a function that I need to write unit tests for. Within this function, I am comparing the global objects window and parent using const isEqual = (window === parent). I am wondering what would be the most effective way to mock ...

Having trouble loading image on web application

Currently, I am facing an issue while attempting to add a background image to an element within my Angular web application. Strangely enough, the relative path leading to the image seems to be causing my entire app to break. https://i.stack.imgur.com/b9qJ ...

Observing the World with TypeScript

Sorry, I am quite new to this and facing a bit of confusion. So, I have a CalendarService which includes a method called getYear(id: string). The structure of my Year model is as follows: export class Year { id: string; number: Number; months: ...

Issue with subscribing to nested observables, unable to successfully unsubscribe

My app is using Firebase auth with Firestore (https://github.com/angular/angularfire2). Despite my efforts to unsubscribe from all observables fetched from Firestore before signing out, I keep encountering a "FirebaseError: Missing or insufficient permissi ...

"Unindexing data in Angular: A step-by-step guide

Can someone help me figure out how to delete an item by index in Angular? I have a parameter and a remove button, but when I tried putting my parameter inside the remove button it didn't work. How can I fix this? deleteRowFiles(rowIndex: number){ th ...

A TypeScript interface or class

Just had a lively discussion with a coworker and wanted to get some clarification. When shaping an object in TS, should we use a class or an interface? If I need to ensure that a function returns an object of a specific type, which one is the best choice? ...

Trouble with accessing Dynamic StyleSheet properties based on type restrictions

I have successfully developed a functional component in React Native that supports both light and dark theme styles. const lightThemeOverrides = StyleSheet.create({ <light_override_styles_here> }); const styles = StyleSheet.create({ <styles_here&g ...

How to redirect to Login page post password update in Angular and Firebase?

Hello, I'm currently working with Angular and Firebase for authentication purposes. I have a quick query: Is there anyone who knows how to set up a redirect to the login page after successfully resetting a password? I have a forgot password page tha ...

The collaboration between Redux's combineReducers and the power of TypeScript

I'm facing a challenge with using react-intl-redux and redux-form in my react app, specifically when working with combineReducers. Despite trying multiple approaches, I haven't been able to resolve the issue. react-intl-redux import { combineRe ...

What is the equivalent of getElementById in .ts when working with tags in .js?

Looking to incorporate Electron, Preload, Renderer with ReactJS and TypeScript into my project. <index.html> <body> <div id="root" /> <script src='./renderer.js'/> </body> <index.ts> const root = Re ...

Error encountered in Next.js: The function 'useLayoutEffect' was not successfully imported from 'react' (imported as 'React')

I've been in the process of migrating an application from CSR (using webpack only) to SSR, and I'm utilizing Next.js for this transition. Following the migration guide provided by Next.js for switching from vite (specifically focusing on parts r ...

Ways to modify environment variables in Angular 6 without the need to rebuild

Typically, I store my API URLs in the environment.ts file. However, when deploying builds to multiple clients with different API URLs, I find myself creating separate builds for each client after adjusting the environment variables. Is there a solution th ...

How can I extract just the initial 2 letters of a country name using AmCharts maps?

Having trouble with Amcharts maps. I have a map that displays countries as United States, but I only want them to show as US. Is there a country formatter available for this issue? Any help is appreciated. ...

Avoid using propTypes for props verification

Looking for a solution to handle multiple props on a button: interface buttonProps { secondary?: boolean; tertiary?: boolean; width?: number; children?: any; icon?: string; } If the button includes an icon without any children, how can ...

What is the best way to create an assertion function for validating a discriminated union type in my code?

I have a union type with discriminated properties: type Status = { tag: "Active", /* other props */ } | { tag: "Inactive", /* other props */ } Currently, I need to execute certain code only when in a specific state: // At some po ...

Exploring Angular - Is it possible to automate testing for a disabled field using Selenium Protractor?

For my MEAN stack project, I am implementing Selenium webdriver to conduct frontend UI testing. There is a field that is non-editable. Please refer to the attached image: Image How can I verify that this field cannot be edited? it('not edit th ...

"Sending the selected pass selector as a parameter to the dispatched action is causing a typing

When a selector changes its value, I want to trigger an action. To achieve this, I passed the selector with a subscription instead of passing an observable. selectedSchedulingsOnPopup$ = this.store.pipe(select(selectSchedulingsByBranch)); this.store.disp ...

What is the method for utilizing string interpolation in Angular/Typescript in order to retrieve a value from a variable?

I have a variable called demoVars, which is an array of objects with properties var1, var2, and var3. In my component class, I have a variable named selectedVar that holds the name of one of these properties: var1, var2, or var3. I want to dynamically pu ...

Using Material UI with React and TypeScript

I need some assistance with organizing my menus correctly in React using TypeScript. Currently, they are displaying on top of each other instead of within their respective category menus. I have been struggling to find a solution and would appreciate any h ...

Visual Studio is refusing to highlight my code properly, intellisense is failing to provide suggestions, and essential functions like go to definition are not functioning as expected

Due to a non-disclosure agreement, I am unable to share any code. However, I am experiencing an issue with Visual Studio not highlighting my code or allowing me to utilize its built-in tools. While I can rebuild the project, I cannot edit or access any fil ...