Unable to retrieve JSON data using ng-for

I am dealing with JSON data that contains nested arrays and objects, specifically

Stores[]--->Products[]--->ProductDetails--->ProductTags[]
. Initially, I want to display all the data by writing the following code:

service

export class StoreService {
  //private myurl: string ="apidata/products.json"
  constructor(private _http: Http) {}
  getProducts(): Observable < any > {

    let apiUrl = './assets/products.json';
    return this._http.get(apiUrl)
      .pipe(map((response: Response) => {
        const data = response.json();
        return data;
      }));
  }

store component:

export class StoreComponent implements OnInit {
  products = [];

  constructor(private _storeService: StoreService) {}

  ngOnInit() {
    this._storeService.getProducts()
      .subscribe(data => {
        this.products = data;
        console.log(data)
      });
  }

}

html

<h2>store</h2>
<ul>
  <li *ngFor="let p of products">{{p}}</li>
</ul> 

However, when trying to render the data, I encounter the following error:

Error trying to diff '[object Object]'. Only arrays and iterables are allowed

Answer №1

If you're encountering an error, it could mean that your data is in the form of an object or map rather than an array.

To utilize *ngFor in your template, your data must be structured as an array instead of an object.

An alternative solution introduced by the Angular team is a pipe called "keyvalue" in version 6.1. This allows you to iterate over an object within your Angular template.

Let's say your object resembles the following:

const user = {
    name: 'xyz',
    age: 30,
    gender: 'male'
};

In your template file, you can iterate through this object like so:

<ul>
    <li *ngFor="let data of user | keyvalue">
        Key : {{data.key}} and Value : {{data.value}}
    </li>
</ul>

For more information about this pipe, please visit this link.

Answer №2

When you encounter this error, it usually means that you are passing an Object instead of an iterable data structure to the *ngFor. The *ngFor directive specifically requires an array for iteration.

To resolve this issue, ensure that when you assign data to this.products, the variable data is actually an array.

UPDATE:

As evident from the console log screenshot:

https://i.sstatic.net/owfMC.png

The variable data is found to be an object and not an array. However, properties like PriceFilter, Stores, and GenderFilter on that object contain arrays. To display stores, you can follow this approach:

export class StoreComponent implements OnInit {
  stores = [];

  constructor(private _storeService: StoreService) {}

  ngOnInit() {
    this._storeService.getProducts()
      .subscribe(data => {
        this.stores = data.Stores;
        console.log(data)
      });
  }

}

Update the template as follows:

<h2>Store</h2>
<ul>
  <li *ngFor="let store of stores">
    <h4>Products:</h4>
    <ul>
      <li *ngFor="let product of store.Products">
        <p>Product Id: {{ product.ProductId }}</p>
        <p>Product Title: {{ product.ProductTitle }}</p>
        ...
      </li>
    </ul>
  </li>
</ul> 

Answer №3

If you're encountering this error, it may be due to your data (products) being returned as an object {} instead of an array []. Make sure to check your HTTP Response or make adjustments to your backend API.

For example, you can try assigning this.products = data.Stores; (if you want to iterate over stores).


UPDATE

Based on the link provided in the comments section, you should modify your code like this:

this.products = data.Stores;

Then, update your HTML template:

<div *ngFor="let p of products">
    <ul>
      <li *ngFor="let item of p">
       <-- Extract what you need from your product object here --!>
      </li>
    </ul> 
</div>

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 Json to redirect actions in MVC architecture

Intent: The aim of this code is to utilize JSON to save all the contents and then redirect to an action. Issue: However, the current redirection using JSON is not functioning as intended. return new JsonResult { Data = new { status = status } }; For you ...

What is the best way to display the output in the view using CodeIgniter?

Seeking guidance on retrieving an array result in the view returned from a controller. This result is obtained through an api call using json. The goal is to showcase these results in the view where there is already a design implemented for display. How ca ...

Generate a JSON file from the database

Apologies for any language errors. I'm attempting to convert data into JSON format for a database. Everything seems to be set up correctly, but the output is incorrect. Here is the link I've generated: . Whenever I check the validity of the site ...

What is the method for determining the mean of a given set of numbers?

Upon parsing data from the server, here is a snippet of the JSON: { "main": [ { "id": "12345" } ], "parameter": [ { "temp": "30.00", "acc": "3.00", "moisture": "200.00", ...

Indicate the type of content returned by a Controller

I'm dealing with a metrics.controller.ts file that looks like this: import { Controller, Get } from '@nestjs/common'; import { ApiOperation, ApiResponse, ApiUseTags, ApiModelProperty } from '@nestjs/swagger'; import { PrometheusSe ...

Automatically clear out table rows once the maximum row limit is reached, then append new data using the WebSocket data in JavaScript

Recently, I delved into JavaScript and faced a dilemma with my Bitcoin Price update dashboard. The data is streaming in through an external WebSocket, updating the prices every second. But here's the catch - the table rows are going crazy! To maintain ...

What are the best strategies to guard against JsonConvert Deserialize object errors in cases where an object class property receives unexpected data?

When converting Json data responses into C# classes using http://json2csharp.com, I have encountered a common issue. If certain parts of the Json are missing when generating the classes, it can lead to an incomplete set of class properties, resulting in un ...

Ways to access information from a SQLite database using Angular

I am a beginner in front-end/back-end communication and I need guidance on how to retrieve data from a SQLite db file to populate a page in my Angular project. I have no idea where to begin, so any resources you can recommend would be greatly appreciated. ...

Ways to convert a JSON file into a ListView using Volley

I'm currently developing an app that requires fetching data from the internet, such as names and email addresses. I followed tutorials on using Volley to parse a JSON file and successfully retrieved the data. However, I encountered an issue when tryin ...

Convert JSON by deserializing and serializing using /UI2/CL_JSON

I am looking to convert JSON data. Currently, I am receiving the following output: "0000010006 GLAESS", but my desired output is {"customer_id":"0000010006","customer":"GLAESS"} TYPES: BEGIN OF ty_field, ...

Establish a connection to Cosmos DB from local code by utilizing the DefaultAzureCredential method

I've created a Typescript script to retrieve items from a Cosmos DB container, utilizing the DefaultAzureCredential for authentication. However, I'm encountering a 403 error indicating insufficient permissions, which is puzzling since I am the ad ...

Tips for merging data gathered from an Observable with additional information from a secondary request

So I'm on a mission to enhance my knowledge by utilizing a service that fetches a list of Posts and then for each post, making another call to retrieve the associated comments. The data I'm working with can be found at https://jsonplaceholder.ty ...

Obtaining a Slick Component Instance with the help of View Child

I am a beginner in angular and I am currently working on implementing a paginated carousel using the ngx-slick plugin. However, I am facing an issue where I need the carousel to start from index 1 instead of 0 when it loads in the template. The ngx-slick p ...

How to Utilize Class Members in a Callback Function in Angular 12 with Capacitor Version 3

When I click the "Device Hardware Back Button" using Capacitor 3.0, I'm trying to navigate to the parent component with the code below. The device back button is working correctly, but I'm facing an issue where I can't access class members i ...

invoking a function within an object in Typescript

export class MockedDataService { constructor(private Session: SessionService) {} private getMockedResponse(name:string){ return ""; // placeholder for the response data, will be a promise } public mocked:{ products:{ ...

Difficulty in activating or deactivating form controls in Angular 2 upon receiving an HTTP response

When using formcontrol in Angular, I encountered an issue where I tried to disable the form control based on a variable assigned from an HTTP response. Angular2 gave me a warning message. The warning mentioned that it's not recommended to use the dis ...

The function within the Context Hook has not been invoked

My attempt to implement a signin method using the context hook is not working as expected inside the AuthContext file. When calling the signin method from the Home Page, neither the console.log nor the setUser functions are being executed inside the AuthC ...

What exactly does "blocking and tackling" refer to in the Angular2 documentation?

As I delved into the online documentation for angular2, I stumbled upon a puzzling term - "blocking and tackling" in the ADVANCED - Angular Module chapter (https://angular.io/docs/ts/latest/guide/ngmodule.html). ... "It's all just basic blocking and t ...

Using jQuery to interact with a web service - overcoming cross-domain restrictions

Attempting to connect to a WCF service using a jQuery client. Referencing this specific example: http://www.codeproject.com/KB/aspnet/WCF_JQUERY_ASMX.aspx#4 Everything functions properly when the client webpage is on the same domain as the service. Howe ...

Is Angular2 the Perfect Fit for Custom HTML Webresources in Dynamics CRM 2016?

Has anyone experimented with integrating Angular2 for custom webresource development in Dynamics CRM 2016? I searched for resources but only came across tutorials on using AngularJS, such as this one ...