Oops! We encountered an error - the object type '[object Object]' is not supported by NgFor. Remember, NgFor only works with Iterables like Arrays. This issue may be related to nested JSON data

I am attempting to bind the data from a nested Json file provided below. Unfortunately, I am encountering an error that states: "Cannot find a differ supporting object '[object Object]' of type 'object'. ngFor only supports binding to Iterables such as Arrays." As a beginner, any guidance would be greatly appreciated.

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { RestProvider } from './../../providers/rest/rest';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {
   weapons: any;
   errorMessage: string;

  constructor(public navCtrl: NavController, public rest: RestProvider) {}

 ionViewDidLoad() {
  this.getweapons();
}

 getweapons() {
   this.rest.getweapons()
      .subscribe(
        weapons => this.weapons = weapons,
        error =>  this.errorMessage = <any>error);
 }

}

HTML


<ion-content padding>
    <ion-list>
      <ion-item *ngFor="let c of weapons">
        <h2>{{c.weapon_category.weapons[0].name}}</h2>
      </ion-item>
    </ion-list>
</ion-content>

Service


import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { map, catchError } from 'rxjs/operators';

@Injectable()
export class RestProvider {
  baseUrl:string = "http://localhost:3000";

  constructor(private httpClient : HttpClient) {}

  public getweapons(): Observable<{}> {
    return this.httpClient
      .get(this.baseUrl + '/categories')
      .pipe(
          map(this.extractData),
          catchError(this.handleError)
        );
      }

      private extractData(res: Response) {
        let body = res;
        return body || { };
      }

      private handleError (error: Response | any) {
        let errMsg: string;
        if (error instanceof Response) {
          const err = error || '';
          errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
          errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
      }

}

Json

{
  "weapon_category": {
    "weapons": [
        {
          "name": "AK",
        }
      ]
    }
}

Answer №1

When dealing with objects, it's common to encounter this error message:

Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

To resolve this issue, make sure to access the array by using weapons.weapon_category.weapons.

Modify your template like so:

<ion-item *ngFor="let weapon of weapons?.weapon_category?.weapons">
    <h2>{{weapon.name}}</h2>
</ion-item>

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

Guide to incorporating Angular 2 code into your Rails application

As a beginner in Ruby on Rails, I have recently learned some CRUD functionalities with RoR. Additionally, I am just starting my journey with Angular 2 and currently learning the basics. I noticed that RoR has its own HTML template engine similar to Angula ...

Access the elements within arrays without using the square brackets

I am trying to access data from a list, but I am having trouble using square brackets []. The getTalonPaie function calls the get method from the HttpClient service and returns an observable with multiple values. However, when I try to store these values i ...

Angular 5 - Keeping track of variable updates

I've searched various topics on this issue, but none seem to address my specific problem. I need a way to detect changes in the properties of a component without having to convert the variable into an array or iterable. I tried using Subject, but coul ...

Transmitting messages from a cross-domain iframe to the parent window

In my parent component, I am embedding an iframe from a different domain. The iframe contains a button that when clicked, I need to capture the event and pass it back to the parent component. I have experimented with using window.postMessage and window.ad ...

Utilizing References in React Components

One of the challenges I am facing involves a Container that needs references to some of its child components: const Container = () => { const blocks: HTMLDivElement[] = []; return ( <div> <Navigation currentBlock={currentBlock} ...

Tips for linking an Express JS server to an Angular 6 file?

I have been researching how to create a user login system using Express, Node.js, and Angular. However, I haven't found a clear answer on how to add new pages with Angular. Can someone guide me on the process and recommend the necessary modules to use ...

Is there a way to implement this toolbar in Ionic Angular?

https://i.sstatic.net/sGd1o.png I am looking to replicate the toolbar shown in the image above using Ionic. As a beginner in Ionic development, I am finding it challenging to translate the design into code. I attempted to use a grid layout, but the varyin ...

Steps to retrieve an image file from the assets directory in Angular 7

After using 'ng new my-app' to create an Angular app, the folder structure looks like this: my-app |- e2e |- node_modules |- src |- assets |- images |- smile.jpg What is the best way to access my image from the ...

Here are some steps to turn off browser autocomplete for a p-inputMask field

I need help in disabling the browser autocomplete on a field that uses p-inputMask. I have tried using autocomplete="nope" on other fields and it works perfectly, but for this specific case, it doesn't seem to work. Can anyone point out what I might b ...

The property 'x' is not found on 'Reel' type in this context

Creating a custom class extending Container in PIXI.js: export class CustomContainer extends Container { constructor(width: number, height: number) { super(); var sprite: Sprite = Sprite.fromImage("assets/images/elephant.png"); ...

Tips on customizing the appearance of the dropdown calendar for the ngx-daterangepicker-material package

Is there a way to customize the top, left, and width styling of the calendar? I'm struggling to find the right approach. I've been working with this date range picker. Despite trying to add classes and styles, I can't seem to update the app ...

using outlines for FontAwesome icons in React Native

I am struggling to use the fontAwesome + icon in the middle of a circle as one item. I have tried placing it inside a circle icon, but it doesn't seem to work properly. import IconFA from 'react-native-vector-icons/FontAwesome'; < ...

Utilizing a customized TypeScript Rest Client from Swagger in Angular 2

In my current project, I am developing a Meteor web application using Angular 2 and TypeScript. To interact with a REST API, I have utilized Swagger Codegen to generate client code. However, I am facing a challenge as there are no example implementations a ...

A guide on utilizing dotenv to access .env file variables in TypeScript

I'm currently facing an issue with utilizing a .env file for storing API keys in a TypeScript React project. The .env file is placed at the project's root directory, and I'm attempting to retrieve its variables from src/index.tsx using proce ...

The error message "ng2-test-seed cannot be found - file or directory does not exist"

I've been attempting to work with an angular2 seed project, but I'm encountering some challenges. https://github.com/juliemr/ng2-test-seed When I run the command: npm run build I encounter the following error: cp: cannot stat ‘src/{index.h ...

When trying to run "ng s -o/ng s/ng build" commands in Angular Cli, there is an issue where no output is displayed

Running "ng serve", "ng serve -o", and "ng build" does not display any output. I am in need of Angular for my project, so if anyone can offer assistance, please help me. https://i.sstatic.net/SmjaL.jpg ...

What is the reason behind the input value becoming empty after a reset?

Currently, I am working with an input element reference: @ViewChild("inputSearch", { static: false }) This is how the template looks like: <input tabindex="0" type="text" (keydown)="keydownInputSearch($event)" #inputSearch autocomplete="off" ...

Creating a custom Angular HTTP interceptor to handle authentication headers

Necessity arises for me to insert a token into the 'Authorization' header with every HTTP request. Thus, I created and implemented an HttpInterceptor: @Injectable() export class TokenInterceptor implements HttpInterceptor { constructor(public ...

Access the raw data value of the parent node using the "val()" method from a child reference within Cloud Functions for Realtime Database

Suppose I'm indicating a path in my TypeScript/JavaScript code function like this: exports.sendNotification = functions.database.ref('shops/countries/{countryName}/shopAddress/{currentShopAddress}') .onWrite((snapshot,context) => { ...

What is the solution for breaking a querySnapshot in Firestore?

Is there a way to exit a querysnapshot loop prematurely? I attempted using a for loop, but I keep encountering the following error message. How can this error be resolved or is there an alternative method to break out of a snapshot loop? code return ...