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

Personalized Functions Using Material Design Expansion Panel Header Icon

Here's a unique material design accordion with an icon added to the panel header. I want to invoke my function 'myFun()' on click event, but currently, the expansion panel is toggling each time it's clicked (which is not the desired beh ...

TS2531: Potentially null object

I am facing an issue in my React-TypeScript project with the following code snippet. Despite having null checks, I am still getting an error "object is possibly null" while running the app. The error specifically occurs in the last part of the if conditio ...

What is the best way to extract all Enum Flags based on a Number in TypeScript?

Given: Enum: {1, 4, 16} Flags: 20 When: I provide the Flags value to a function Then: The output will be an array of flags corresponding to the given Enum: [4, 16] Note: I attempted to manually convert the Enum to an array and treat values as numb ...

Troubleshooting TypeScript in Visual Studio Code

Currently, I'm attempting to troubleshoot the TypeScript code below using Visual Studio Code: class Student { fullname : string; constructor(public firstname, public middleinitial, public lastname) { this.fullname = firstname + " " + ...

Guide to leveraging clsx within nested components in React

I am currently using clsx within a React application and encountering an issue with how to utilize it when dealing with mappings and nested components. For instance: return ( <div> <button onClick={doSomething}>{isOpened ? <Component ...

Using mat-form-field with the outline appearance seems to be causing some issues

When I change the body direction to RTL, the mat-form-field with appearance"outline" seems to have some issues. If you go to the https://material.angular.io site and navigate to the Form field examples, under the Form field appearance variants section, yo ...

Angular 4+ directive allowing interaction with the NgModel of a component

I'm looking to update styles based on the state of NgModel.control. To keep it DRY, I was thinking that a directive for reading the NgModel component state could be the solution. Is this actually feasible? I haven't been able to find any guidanc ...

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 ...

Guide to implementing a universal animated background with Angular components

I'm having trouble figuring out why, but every time I attempt to use a specific code (for example: https://codepen.io/plavookac/pen/QMwObb), when applying it to my index.html file (the main one), it ends up displaying on top of my content and makes ev ...

The bidirectional data binding between two components is only functioning for the initial letter

Encountering a peculiar error that I have been researching with no luck in finding a solution. Most of the related findings are outdated and ineffective. Error Message An error is triggered when two-way binding to a property: 'Expression has chang ...

Elevated UI Kit including a setFloating function paired with a specialized component that can accept

I am currently experimenting with using Floating UI alongside various custom React components. These custom components create internal element references for tasks like focus and measurements, but they also have the capability to accept and utilize a RefOb ...

Troubleshooting the issue with the HTTPClient get method error resolution

Currently, I am attempting to capture errors in the HTTP get request within my service file. Below is the code snippet: import { Injectable } from '@angular/core'; import { PortfolioEpicModel, PortfolioUpdateStatus } from '../models/portfol ...

Can you provide input to the reducer function?

In the creator, an action is defined like this: export const actionCreators = { submitlink: (url: string) => <SubmitLinkAction>{ type: 'SUBMIT_LINK' } } In the component that calls it: public render() { return <div> ...

Tips for identifying unnecessary async statements in TypeScript code?

We have been encountering challenges in our app due to developers using async unnecessarily, particularly when the code is actually synchronous. This has led to issues like code running out of order and boolean statements returning unexpected results, espe ...

Typescript encounters issues when assigning declaration as TRUE

Currently, I'm working on a project in Angular 2 and attempting to create TypeScript definitions for it so that it can be exported as a library. I have various services set up that make HTTP requests to components, all structured similarly to the cod ...

"Error message: Trying to import a component in Angular, but encountering a message stating that the component has no exported

When creating a component named headerComponent and importing it into app.component.ts, an error is encountered stating that 'website/src/app/header/app.headerComponent' has no exported member 'headerComponent'. The code for app.headerC ...

Troubleshooting: Inability to Use Type Assertions while Retrieving Data from

Struggling to retrieve and analyze complex data from Firebase for computation and Cloud Function execution. The format of the data is not aligning with my needs, as shown in this example: interface CourseEvent { coucourseGroupType: string; date: Fireb ...

Most effective method for converting a table of data to TypeScript

Searching for an effective method to map a table of enum (or interface) data to the correct location. For instance, Smoke Sensor - Push Button can only be linked to SS - PI SYMBOL and Smoke Sensor - PushButton can only be associated with 000 - TTT PARAMET ...

Switch the following line utilizing a regular expression

Currently, I am facing a challenge with a large file that needs translation for the WordPress LocoTranslate plugin. Specifically, I need to translate the content within the msgstr quotes based on the content in the msgid quotes. An example of this is: #: . ...

Guide on importing npm packages without TypeScript definitions while still enabling IDE to provide intelligent code completion features

I am currently utilizing an npm package that lacks type definitions for TypeScript. Specifically, I'm working with the react-google-maps library. Following their recommended approach, I have imported the following components from the package: import ...