Adding data to an array from a JSON source using Angular 5

When I receive a response from an endpoint, it looks like this:

{
  "data": [{
    "volume": 4.889999866485596,
    "name": "Carton03",
    "weight": 5.75,
    "storage": 3
  }, {
    "volume": 2.6500000953674316,
    "name": "Carton02",
    "weight": 4.5,
    "storage": 2
  }, {
    "volume": 1.4500000476837158,
    "name": "Carton01",
    "weight": 5,
    "storage": 1
  }],
  "response": "true",
  "type": "Storages"
}

In the following code snippet, I attempt to create an array in my component:

export class StorageComponent {
   private data: any;
   private stors: Storage [];

   constructor (private storageService: StorageService  ) {}

   storage () {
     this.data =  this.storageService.Storage(); 
     //storageService.Storage is an assistant service that parses the response 
     // and returns only the data-array of the response
     for (let i = 0; i < this.data.data.length; i++) {
      const storages = this.data.data[i];
      console.log(storages.storage);
      console.log(storages.name);
      console.log(storages.weight);
      console.log(storages.volume);
      this.stors[i] = storages;  
     }   
  }
}

I utilize a const called 'storages' to inspect and evaluate the data, which works correctly.

The issue arises when I try to populate my 'stors' variable, which is an array of the Storage model with attributes like storage, name, etc.

On the last line where I'm trying to do this, I encounter the error:

Cannot set property '0' of undefined

Does anyone have any ideas on how to resolve this?

Answer №1

An issue has arisen in which the error message indicates that on the initial loop iteration, the assignment to this.stors[0] cannot be executed due to its undefined nature. The stors attribute lacks initialization. To rectify this, contemplate the following adjustment:

constructor (private storageService: StorageService) {
    this.stors = [];
}

Answer №2

To properly initialize the stors property, make sure to do it this way:

private stors: Storage[] = [];

You can also set initial values for other properties like so:

private data: any = null;

It's recommended to initialize arrays directly in the properties rather than in the constructor or ngOnInit.

By initializing your class properties, you can prevent unexpected behavior from occurring.

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

`Navigating through Indices Manually`

Is there a way to manually check the indices of a given integer number? For instance, I want to determine if the indices are even or not. Would converting it into an array and then checking for indices be the best approach here? I'm feeling a bit lost ...

transforming information into hierarchical JSON format using C#

I am working with a data table that has the following structure: Table structure of given data. The table consists of four columns namely Id, Name, Salary, and RefId. In the RefId column, we store the ID of the parent object. Below is the modal class for ...

Instructions on importing a particular column from a .csv file into a two-dimensional array using Python

I have a .csv file with the following data: ID Name Zip Lat Lng 1 John 1001 23.234 54.234 2 Sarah 1002 24.234 54.231 3 Emily 1003 26.234 54.232 From this file, I am interested in extracting only the Name, Lat and Lng columns. How can I store ...

Angular 2 - Conceal Table Panel if there is no data in the table

I am using *ngFor to generate panels that contain tables. Each table uses *ngFor to create <td> elements for each item in a dataset. Sometimes the table will have empty rows. Is there a clever way to hide the panel when the table has no children? I ...

Angular: ChangeDetection not being triggered for asynchronous processes specifically in versions greater than or equal to Chrome 64

Currently, I'm utilizing the ResizeObserver in Angular to monitor the size of an element. observer = new window.ResizeObserver(entries => { ... someComponent.width = width; }); observer.observe(target); Check out this working example ...

Error: Cannot convert a value of type java.lang.String to a JSONObject in JavaJSONException

I just started exploring android development and stumbled upon an app that would complement the web scraper I've been diligently working on. This app fetches information from a MySQL database using a PHP script and presents it on your android device. ...

How to utilize JQ to find specific key, value pairs within a list of objects sharing identical keys

Consider the JSON object provided below: { "company1": { "employees": [ { "name": "John", "title": "CEO" }, { ...

Transmitting an array of objects via Ajax to PHP

Assistance Needed: I have created my object using the following code: var data = []; $("#report-container [id^='report-']").each(function(index) { var reportObject = { "subject" : "", "photo" : "", "rating" : "", ...

Having trouble getting webpack to transpile typescript to ES5?

Despite following official guides and various tutorials, I am still facing an issue with compiling my code to ES5 using TypeScript and webpack. The problem is that the final bundle.js file always contains arrow functions. Here is a snippet from my webpack ...

Rails feature allowing users to select records and receive JSON data of their choices

Hello, I'm using a form in Rails and here is the code: <%= form_tag getjson_products_path do %> <% @products.each do |product| %> <%= check_box_tag "product_ids[]",product.id , false%> <%= product.name %> <%= p ...

Exploring Angular Testing: Unraveling Chained HTTP Requests with the Power of rxjs

I've been attempting to write unit tests for a function in my service that carries out a POST request followed by a GET request. I'm using switchMap to handle this, but running into an issue where the HttpTestingController match function isn&apos ...

The request for PUT, POST, and DELETE methods has been terminated

Issue Encountering the following problem: Scenario Pinning down the exact reason and providing detailed information is proving to be a challenge. In essence, the setup involves an Angular + Express.js application, MySQL for the database, Nginx as a pro ...

What is preventing the exclusion of the null type in this specific situation within Typescript?

type NonNullableCopy<O> = { [p in keyof O] -?: O[p] extends null | undefined ? never : O[p]; }; type Adsa = {a?: number | null} type Basda = NonNullableCopy<Adsa> let asd : Basda = { a: null // Still valid. No errors } Although it see ...

Implement Bootstrap into Asp.Net Core 6 for the scaffolded Identity _Layout.cshtml

In my development environment using VS2022 Preview, I have set up a Single Page Application with Angular and the default project provided by VS2022. To customize the appearance of the Identity pages, I decided to override Bootstrap with a style from Bootsw ...

Angular Error: The first argument has a property that contains NaN

Struggling with a calculation formula to find the percentage using Angular and Typescript with Angularfire for database storage. Encountered an error stating First argument contains NaN in property 'percent.percentKey.percentMale. The properties are d ...

Adding SVG to Component

I am attempting to embed an SVG element (retrieved using http.get()) into a 'icon' component. export class BgIcon { private svgSrc_: string; icon_: Icon; @Input('svg-src') set svgSrc(value: string) { this.svgSrc_ = value; ...

The pagination in React using React Query will only trigger a re-render when the window is in

Currently, I am utilizing React-Query with React and have encountered an issue with pagination. The component only renders when the window gains focus. This behavior is demonstrated in the video link below, https://i.sstatic.net/hIkFp.gif The video showc ...

What is the best way to handle constants in TypeScript?

I am facing an issue with a React component I have created: const myComponent = ({constant}: Iprops) => ( <div> {CONSTANTS[constant].property ? <showThis /> : null </div> ) The error message says 'element implicitly has ...

Tips for accessing the value of a specific key within an object that is nested in an array

I'm attempting to extract the name of the merchant from within this specific array: [ { "model": "inventory.merchant", "pk": 1, "fields": { "merchant_name": "Gadgets R Us", "joined": "2020-01-06T07:16:17.365Z" } }, ...

What is the best way to verify identical array elements in php?

Hey there, I have an array with repeating dates and I want to count the number of times each date appears in the array. However, my current approach is giving me an error message Undefined offset: 0. <?php $array = array('2013-11-28','2 ...