Ion2 Ngfor can only be used with arrays as data sources

Struggling to retrieve JSON data using the http client, but facing an error when trying to display it in the view:

NgFor only supports binding to Iterables such as Arrays

Upon inspecting the console.log output, I noticed that the data is an object containing other objects. https://i.sstatic.net/lE2Hp.png

This is my service code:

@Injectable()
export class DataService {
  data: any;

  constructor(private http: Http) {
    this.data = null;
  }

  load() {

      // Using Angular HTTP provider to fetch and map JSON data to a JS object.
      // Further processing of data before resolving the promise with new data.
    return this.http.get('http://localhost:3000/db') //json url
      .map(res => res);
  }
}

Below is the constructor from my page.ts where the data is being loaded :

constructor(private nav:NavController, navParams:NavParams, http:Http, public service:DataService) {
        this.service.load().subscribe (
            response => {
                this.displayData=response;
                console.log(this.displayData);
            },
            error => console.log ('error in download')
        );
}

The ngfor loop in my page.html:

<ion-card *ngFor="let data of displayData">
</ion-card>

Here is the JSON retrieved from the localhost URL:

{
  "0": {
    "title": "Erreichbarkeit",
    "items": [
      {
        "name": "1",
        "value": "a"
      },
      {
        "name": "2",
        "value": "b"
      },
      {
        "name": "3",
        "value": "c"
      }
    ]
  },
  "1": {
    "title": "Erreichbarkeit 2",
    "items": [
      {
        "name": "1",
        "value": "g"
      },
      {
        "name": "2",
        "value": "f"
      },
      {
        "name": "3",
        "value": "e"
      }
    ]
  }
}

If anyone can pinpoint the issue, please help as it's becoming frustrating.

Answer №1

Your data structure needs to be in the format

[{"title" : ...}, {"title": ...}]
to properly function as an array. Currently, it is structured as an object with properties named 0 and 1. Have you considered updating your Json to look like this:

[
  {
    "title": "Accessibility",
    "items": [
      {
        "name": "1",
        "value": "a"
      },
      {
        "name": "2",
        "value": "b"
      },
      {
        "name": "3",
        "value": "c"
      }
    ]
  },
  {
    "title": "Accessibility 2",
    "items": [
      {
        "name": "1",
        "value": "g"
      },
      {
        "name": "2",
        "value": "f"
      },
      {
        "name": "3",
        "value": "e"
      }
    ]
  }
]

Incorporate this updated structure into your view:

<ion-card *ngFor="let data of displayData">

    <ion-card-header>{{data.title}}</ion-card-header>   

    <ion-card-content >
        <p *ngFor="let item of data.items">{{item.name}}: {{item.value}}</p>
    </ion-card-content>

</ion-card>

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

Utilizing Type Script 1.8 with Visual Studio 2017 for older projects: A step-by-step guide

After installing Visual Studio 2017, I encountered a TypeScript error when trying to run my project. It seems that VS 2017 is using TypeScript 2.1.5, while my application was designed for TypeScript 1.8. Is there a way to make VS 17 utilize TypeScript 1.8 ...

What is the most effective way to convert an array into an object using index signatures and classes as types?

I am facing a challenge involving transforming an array of type A into an array of type B and then passing it to a class called Person as input data. I am currently stuck and uncertain about how to accomplish this task. Here is the definition of Type A an ...

Testing the selection of dropdown values in Angular2 using unit tests

I have a dropdown menu for selecting countries. It defaults to a pre-selected value, and when the user changes it, they are redirected to the corresponding country page. However, I am facing an issue while trying to unit test the default value in the sele ...

Unexpected behavior: Angular post request does not include the expected request body

Embarking on my initial solo Angular project... I am endeavoring to make a post request to my freshly created web service and have implemented the following code: headers = new HttpHeaders( {'Content-Type':'text/plain'} ); l ...

Authenticate the digital signature created with the ED25519 algorithm

My current task involves verifying a digital signature that was signed using ED25519 with typescript Crypto, but I need to verify it in Java using BouncyCastle. The code snippet I am using for verification is as follows: byte[] decodedSign = Base64.getDeco ...

Create Open Graph meta tags dynamically using the MEAN stack, including Angular 2+

I'm currently working on creating unique OG tags for specific item-detail pages. I am using the meta module for Angular from https://github.com/nglibs/meta to generate these meta tags, which work perfectly fine in browsers. However, when it comes to F ...

Service in Angular2 fails to retrieve mock data

UPDATE: I apologize for the error in my code. I have now corrected it by ensuring that then is called inside the service. I am developing a Service that generates mock data (following a similar structure as shown here) but am facing issues retrieving the ...

Can you explain the distinction between 'rxjs/operators' and 'rxjs/internal/operators'?

When working on an Angular project, I often need to import functionalities like the Observable or switchMap operator. In such cases, there are two options available: import { switchMap } from 'rxjs/operators'; or import { switchMap } from ' ...

What are the steps to generate a customizable datatable with various columns and information?

My application allows users to select options from a dropdown menu, which triggers a request and displays the output - typically a table - on the website. The data is always in JSON format, like the examples shown below: '{"columns":["C1","C2"], "dat ...

Which TypeScript AsyncGenerator type returns a Promise?

I am currently in the process of assigning a return type to the function displayed below: async function *sleepyNumbers() { // trying to determine TypeScript type let n = 0; while (true) { yield new Promise(resolve => resolve(n++)); ...

Managing elements within another element in Angular

I am currently exploring the use of Component Based Architecture (CBA) within Angular. Here is the situation I am dealing with: I have implemented three components each with unique selectors. Now, in a 4th component, I am attempting to import these compon ...

Immediately after setting up a fresh Angular 13 project, addressing the npm ERR! regarding the missing peer dependency ajv@^6.9.1 requested by [email protected]

Recently, I initialized a fresh Angular project by running npx @angular/cli@13 new Ubisoft.SupplierPortalNext.Spa and then performed npm install, which resulted in the following warning: npm WARN [email protected] requires a peer of ajv@^6.9.1 but n ...

Learn the process of marking an option as selected within an Angular component

I have an Angular component that displays a question along with a dropdown menu (<select>) to choose from various answers. My goal is to programmatically set one of the options as selected based on certain parameters present in the application' ...

Error: Select dropdown placeholder malfunctioning

Even after trying numerous solutions from various forums, I am unable to make the placeholder display in my code. Maybe a fresh perspective can help spot what I might be missing. view image here I have experimented with using "" as the value, as ...

Understanding the mechanisms of Promise functionality within Typescript can be challenging, particularly when encountering error messages such as "type void is not

Recently, I've delved into the world of Typescript. Despite my efforts to stay true to the typing system, I've encountered a challenge that forces me to resort to using the any type: The issue arises with a function that returns a promise: sav ...

Error message: Failure to define class methods when exporting the class from a file

In my project, I have defined a class called BinarySearchTree in a file named a.js. This class has been exported and then imported into another file where it is used as the parent class for a different class called Traversal. However, I encountered an issu ...

In Angular, ensure validation for dropdowns is enforced when the selected value is "yes" in the 2nd dropdown. This means that validation must be applied to the

I am currently working on validation for a set of dropdown menus. There are three dropdowns in total: 1) The first and second dropdowns are mandatory, but for the third dropdown, I need to implement a logic. The logic is that if the value of the second d ...

Change Json data into a TypeScript class [ts]

I have the following JSON data: {"mapData":{"test":"success","publicKey":""},"statusCode":200,"message":null} How can I convert this JSON to a TypeScript class? The mapData contains anonymous values: It may be {"test":"success","publicKey":""} Or it m ...

I am facing an issue where I am unable to execute 'npm run server' after compiling an Angular app using 'npm run

I encountered an issue with my Angular app that is utilizing Angular Universal. After bundling the app using npm run build:prod, everything seemed to be fine without any errors. However, when I attempted to view the app in the browser by running npm run se ...

Leverage the Node Short ID library in conjunction with Angular 6 using TypeScript

I attempted to utilize the node module within an Angular 6 typescript environment. Step one: npm i shortid Within my TypeScript class: import { shortid } from 'shortid'; let Uid = shortid.generate(); However, I encountered an error stating ...