The Angular/Typescript framework encountered an issue when trying to locate a differ that can handle an object of type 'object'. NgFor is limited to binding with Iterables like Arrays and is not compatible with plain objects

I am currently utilizing Angular for my project.

I am attempting to call an API to fetch data from it, but I keep encountering this error:

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

This is how my service is structured:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { User } from '../Models/user.model';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  apiUrl = 'myurl is in here but i cannot show'

  constructor(private _http: HttpClient) { }

  getUsers(){
    return this._http.get<User[]>(this.apiUrl);
  }
}


Here is the user model:

export class User {
    // User model properties here
}

This is how the TypeScript component utilizes it:

import { Component, OnInit } from '@angular/core';
import { User } from 'src/app/Models/user.model';
import { DataService } from 'src/app/Services/data.service';
 
 

@Component({
  selector: 'app-side-nav-alerts',
  templateUrl: './side-nav-alerts.component.html',
  styleUrls: ['./side-nav-alerts.component.css']
})
export class SideNavAlertsComponent implements OnInit {
users$: User[];
  constructor( private dataService : DataService) { }

  ngOnInit(){
    return this.dataService.getUsers()
    .subscribe(data => this.users$ = data)
  
  }

}


Here is the HTML code:

<div *ngFor = 'let user of users$' style="text-align: center;">
    <h2>{{user.name}}</h2>
    </div>

Any suggestions on how I can properly loop over the data retrieved from the API? I am considering converting it to another data type but I'm unsure how to proceed with this.

Answer №1

Consider trying this approach:

ngOnInit(){
  this.users$ = this.dataService.fetchUsers()  
}

instead of

ngOnInit(){
  return this.dataService.fetchUsers()
  .subscribe(data => this.users$ = data)
}

As the variable "data" contains the actual data, not a Subscription or Observable. Furthermore, there is no need for a return statement in your ngOnInit.

Change

users$: User[];

to

users$: Observable<User[]>;

In your HTML template, make sure to use the async pipe like this:

*ngFor = 'let user of (users$ | async)' style="text-align: center;"

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

Unable to access nested JSON in Angular 2

To sum up, if I use the following code: {{ foo.bar | json }} Assuming foo is a JSON object and bar is a JSON object within foo, Angular 2 will load the data in foo.bar correctly and display the JSON object. However, trying to access foo.bar.baz will resu ...

Passing an Array of Objects from a Child Component to a Parent Component in Angular

I have developed two components named parent and child. These components are linked in app.component.html. In the child component, I have an array of objects that I want to display in the parent component using @Output. My desired output is to show each ob ...

Establishing reducers within Ngrx

I'm currently in the process of setting up a basic Ngrx state management system. # app.module StoreModule.forRoot(reducers), This particular code snippet has been automatically generated using the Ngrx schematics generators. export const reducers: Ac ...

Ways to adjust the ngx-pagination color scheme?

I am looking to customize the background color of ngx-pagination Here is my current code: <pagination-controls class="custom-pagination" id="indicadorPaginationResults" (pageChange)="p=$event" maxSize="9" directionLinks="true" autoHide="true" previ ...

Using Mat-Error for Two Way Binding leads to frequent triggering of ngModelChange事件

I am working with a mat input field that has two-way data binding using ngModel, and I want to add validation using mat-error and formControl. <mat-form-field [formGroup]="myForm"> <input matInput formControlName="myFormName" autocomplete="off" ...

Issue encountered when transferring Angular app to Python Flask

Not sure what information to provide, but I will give as much detail as possible. Currently, my Angular app is running on IIS and utilizing Classic ASP. Everything is working smoothly. There is a dropdown that fetches JSON data to populate a table. Recen ...

Getting started with Angular2 ngrx storemodule reducer - Understanding the process of injecting services into the initialState

const startingState = { // service.fetch(); } How can we inject a service into a reducer? Is it possible to utilize a service within a reducer without a constructor or class? export function personnelHandler(state = startingState, action: PersonnelAction ...

Setting a TypeScript version in Atom: Step-by-step guide

I'm currently grappling with using a specific version of TypeScript in Atom. For an older project that relies on Backbone, the latest TypeScript version doesn't compile properly, so I need to use an earlier one. The closest solution I've co ...

When utilizing Angular, the mat-datepicker is displayed underneath the modal, even after attempting to modify the z-index

I am encountering a problem with a mat-datepicker displaying below a modal in my Angular application. Here are the key details: Html: <div class="col-12"> <mat-form-field appearance="fill"> <mat-label>Start Date ...

Using parametric types as type arguments for other types in TypeScript or Flow programming languages

Consider the various types showcased for demonstration: type TranslateToEnglish<A extends string> = A extends "1" ? "one" : A extends "2" ? "two" : A extends "3" ? "three" : "e ...

What is the process for including an extra track in Twilio Video?

Since updating the twilio-video JS SDK from version 1.x to 2.x, I've encountered an issue when trying to add an additional device. An example of the error message is as follows: ERROR TypeError: transceiver.sender.replaceTrack(...).then(...).finally i ...

``There is an issue with Cross-Origin Resource Sharing (CORS) in a Node.js application utilizing TypeScript

I've encountered some issues with my application, specifically regarding CORS. I suspect it may be due to a misconfiguration on my server. The problem arises when I attempt to create a user in my PostgreeSQL database via the frontend. I have a tsx com ...

undefined event typescript this reactjs

I have come across the following TypeScript-written component. The type definitions are from definitelytyped.org. I have bound the onWheel event to a function, but every time it is triggered, this becomes undefined. So, how can I access the referenced el ...

Exploring Angular 2: Unlocking the Power of Directives within Components

To display a dialog component on the main component page after clicking a button, I used directives in the following way: Within the template: <button id="goToTasksCases" class="btn btn-success btn-lg" (click)="doShowStartNewCase($event)">START A N ...

What is the best way to extract data from a text file that contains multiple data entries separated by pipes (|) using the fs module?

I'm currently utilizing the node.js fs module to read a text file. One thing that I'm wondering is, does the fs module only support reading text files or can it handle other file formats as well? Now, my primary inquiry is if the text file conta ...

Discover the power of native script's two-way data binding in your classes

Is there a way to implement two-way binding in Nativescript? Here is my attempt: The variable CompModel is set to "FA I Test". I am looking for a solution where the data can be bound both ways - initially displaying the value "FA I Test" at the class lev ...

Tips for creating a mapped type in TypeScript that is based on an array

Is there a way to create a function with dynamic properties? function magic(...propertyNames:string[]): { ????? : any } { .... } Could the returned type have properties listed in propertyName? For instance: type ResultType = {alpha:any, bravo:any}; le ...

Is it possible to create dynamic meta tags in Angular that will appear in a Twitter-style card preview?

My project involves building a dynamic website using a Java app that serves up a REST-ish JSON API along with an Angular9 front end. A key requirement is the ability to share specific URLs from the app on platforms like Twitter and Slack, which support Twi ...

Issue with bidirectional data binding in Angular 2 on input element not functioning as expected

Looking at the code snippet below, I have noticed that even though the textchange function is called when the input value changes, the text property of the InputMaskComponent remains constant. I am not able to identify the issue in my code. InputMaskCompo ...

What are some creative ways to emphasize certain dates?

Is there a way to customize mui-x-date-pickers to highlight specific days from a Date array with green filled circles around them? I am using new Date and wondering how to achieve this effect. Below is the code snippet I am currently working with: <Dat ...