Issue: Unable to locate a differ that supports the object '[object Object]' of type 'object'. NgFor can only bind to Iterables like Arrays

I have successfully pulled data from the jsonplaceholder fake API and now I am attempting to bind it using Angular 2 {{}} syntax. However, I encountered an error that states: "Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays." I'm unsure of what I might be doing wrong. Any help would be greatly appreciated. Below is my code snippet along with the error message.

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

import { Component } from '@angular/core';
import {BioService} from './bio.service'
import { Users } from './User';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
values : any;
users: Users[];
errorMessage: string;
mode = 'Observable';

profile = {};
constructor(private bioservice:BioService)
{

}

ngOnInit(){
     this.getHeroes();
     debugger;
}

  getHeroes() {
  this.bioservice.getHeroes().subscribe(data => this.profile = data);
 }

}

HTML Template:

<h1>
<div>
<ul *ngFor= "let user of profile">
<li>{{user.userId}}</li>
</ul>
</div>
</h1>

Service:

        import { Injectable } from '@angular/core';
        import { Http, Response, Headers, RequestOptions } from '@angular/http';
        import {Observable} from 'rxjs/Rx';
        import 'rxjs/add/operator/map';
        import 'rxjs/add/operator/catch';
        import { Users } from './User';


        @Injectable()
        export class BioService {

        private url = 'http://bioapideploy.azurewebsites.net/api/Users';
        private placeholderurl = "https://jsonplaceholder.typicode.com/posts";

          constructor(private http: Http) { }

          getHeroes() {
            debugger;
            return this.http.get(this.placeholderurl)
            .map((res:Response) => res.json());
          }

          private extractData(res: Response) {
            debugger;
            let body = res.json();
            return body.data || { };
          }


          private handleError (error: Response | any) {
            // In a real world app, you might use a remote logging infrastructure
            debugger;
            let errMsg: string;
            if (error instanceof Response) {
              const body = error.json() || '';
              const err = body.error || JSON.stringify(body);
              errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
            } else {
              errMsg = error.message ? error.message : error.toString();
            }
            console.error(errMsg);
            return Observable.throw(errMsg);
          }
        }

Answer №1

Within the AppComponent component, update the code from profile = {}; to profile: any[];

Answer №2

It seems that the async pipe is missing from your *ngFor statement. As the getHeroes() function returns an Observable, you must use the async pipe to inform Angular that the data provided to the *ngFor loop is asynchronous.

<h1>
  <div>
    <ul *ngFor= "let user of profile | async">
      <li>{{user.userId}}</li>
    </ul>
  </div>
</h1>

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

Creating a custom directive in Angular 2 that restricts input to text only

I have recently created a directive that specifically allows only numbers by using key codes. However, I've noticed that when I try to copy and paste text into the text box, it accepts the input but does not display it. Is there a way to utilize &apo ...

Tips for using useState to update only the element that was clicked:

When I click the button to add a step to a chapter, it's adding a step to all chapters instead of just one. What mistake am I making? const example_chapters = [ { id: 1, title: 'Chapter 1'}, { id: 2, title: 'Chapter 2'}, ...

Display the new data from an array that has been created following a subscription to Angular Firestore

I am struggling to access the content of a variable that holds an array from a Firebase subscription. The issue I am facing is that I am unable to retrieve or access the value I created within the subscription. It seems like I can only use the created valu ...

When passing e: EventTarget as a forwarded prop through a wrapper component, Typescript raises an error about the missing "value" property in the onChange function

In my project, there is a custom component called SelectField that serves as a wrapper for rendering label, helper text, and select input (inspired by TextField from @material-UI). The SelectField component exposes props like value and onChange, which are ...

Nest faces difficulty resolving the dependencies required by the TMPController

I've tried everything to fix this error, but nothing seems to be working. tmp.module.ts import { Module } from "@nestjs/common"; import { TMPController } from "./tmp.controller"; import { TMPService } from "./tmp.service"; @Module({ controllers: ...

Interactive Tab content display

I'm working on a tabs component and I need Angular to only render and initialize the active tab instead of all tabs. Is there a way to achieve this? <my-tabs> <my-tab [tabTitle]="'Tab1'"> <some-component></some-co ...

Utilizing the Pub/Sub architecture to integrate the kafka-node library within Node Js

Utilizing the kafka-node module in my NodeJs Microservise project, I am aiming to implement a Pub/Sub (publisher and subscriber) design pattern within the Functional programming paradigm. producer.js const client = new kafka.KafkaClient({ kafkaHost: ...

Dealing with asynchronous operations in a pipeline with fp-ts

I'm currently exploring fp-ts and have been contemplating how to restructure my functions in order to steer clear of nested folds. While many online examples showcase a clean invocation of the pipe function, I am struggling to eliminate the nested fol ...

Guide to utilizing services in Angular 2

As I've developed a service with numerous variables and functions, my goal is to inject this service into multiple components. Each component should have the ability to update certain variables within the service so that all variables are updated once ...

My goal is to eliminate the console error message "@ Angular: GET http://localhost:4200/assets/i18n/1/fr.json 404 (Not Found)" related to missing file

Is there a way to prevent the "GET http://localhost:4200/assets/i18n/1/fr.json 404 (Not Found)" error from appearing in both the console and network of the browser while using Angular? I need a solution for this.custom.translate.loader.ts****** return Obse ...

Ways to generate an Angular 7 component

Seeking guidance on creating an angular 7 component. I have forked a jsFiddle at this link: https://jsfiddle.net/gauravshrestha/fdxsywLv/. The chart in the fiddle allows data points to be dragged up and down. My goal is to convert this into a component whe ...

What is the best way to extract and display data from an API response object in my

{ "_metadata": { "uid": "someuid" }, "reference": [ { "locale": "en-us", ... bunch of similar key:value "close_icon_size" ...

In Angular, encountering difficulty accessing object members within an array when using custom pipes

Here is a custom pipe that I have created, but I am facing an issue accessing the members of the customfilter array, which is of type Item. import { Pipe, PipeTransform } from '@angular/core'; import {Bus} from '/home/pavan/Desktop/Pavan ...

Angular button for opening or closing the menu that redirects the page to a localhost URL

I have implemented a template from the link below into my project. So far, everything has been working fine, but recently I noticed that the menu open/close button is malfunctioning. Whenever I click on the close button while on any page (for example, http ...

Unusual conduct exhibited by a 16th version Angular module?

I've created a unique component using Angular 16. It's responsible for displaying a red div with a message inside. import { ChangeDetectionStrategy, Component, Input, OnInit, } from "@angular/core"; import { MaintenanceMessage } ...

Cookies are not being sent by Angular 2

Currently, I am working on a project that involves frontend development using angular 2 and backend with symfony as the API. However, I am facing an issue where I need to send the PHPSESSID when making a request to symfony, but it is not happening as expec ...

Issue with Angular ngFor not updating radio button value when ngModel is set

Hello, I am fairly new to working with Angular and could really use some assistance with a problem I've run into. Essentially, I am receiving an array of objects from an API like this: [{name: "abc", score: 2},{name: ""def, score: ...

Displaying centered text over a mat-progress-spinner using Angular, Material, and Flex-Layout

In my Angular project, I am utilizing material and flex-layout. One challenge I encountered is centering text inside a mat-progress-spinner element. I attempted to achieve this by using position absolute, but the issue is that it doesn't stay centered ...

Validate if the translation file exists in ngx-translate

Is there a way to determine if a translation file exists for the language obtained from navigator.language using ngx-translate? I am looking to implement something similar to: if( isLanguageAvailable(navigator.language)) { this.translate.use(navigator.l ...

Determining the type of an overloaded method within a generic function

I am currently working on developing a versatile function that can subscribe to an event emitter. The function subscribe is designed to take 3 arguments: event name, event handler, and the event emitter to connect to. I am looking for ways to ensure accur ...