Error in Angular 8: The type of '[object Object]' is an object, whereas NgFor only supports binding to Iterables such as Arrays

I recently started using Angular 8 and I'm dealing with an issue while trying to fetch data from an http get request. I am attempting to iterate through the data using *ngFor but unfortunately encountering this error.

Any suggestions on how to resolve this error would be greatly appreciated.


'[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
student model

export class Student {
    Name: string;
    Sport: string;

}

student.service.ts

    public getData(path: string): Observable<Student[]> {
        return this.http.get<Student[]>(this.mainUrl + path).pipe(
            tap(_ => console.log('fetched data'))
        );
    }

student.component.ts

import { Observable, of } from 'rxjs'; 
import { Student } from 'src/app/models/student';
import { HttpService } from 'src/services/http.service';
import { StudentService } from './student.service';


@Component ({
    selector: 'student',
    templateUrl: 'student.component.html',
    styleUrls: ['student.component.css']
})

export class StudentComponent implements OnInit {
    students: Student[];

    constructor(
        private studentService: StudentService
        ) {
    }

    getStudents(): void {

        let ppp = this.studentService.getData("get_students");
        this.studentService.getData("get_students").subscribe(
            students => { this.students = students }
            // students => {console.log(this.students)}
        );
        console.log(this.students); // prints undefined
    }


    ngOnInit() {
        this.getStudents();

    }   
}

student.component.html

<li *ngFor="let p of students">

  <div>hello</div>
</li> 

Answer №1

Your server is responding with an object containing the data you need to extract from it

public fetchData(path: string): Observable<Student[]> {
  return this.http.get<Student[]>(this.mainUrl + path).pipe(
    map(({ student }) => student)
  );
}

This code should work fine if your server is sending an actual array back. If you're still encountering issues, try converting the response into an array format.

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

IE11 displaying empty placeholders instead of PrimeNG icons after deployment on server

Currently, I am in the midst of an Angular project that heavily relies on PrimeNg for various components. While everything runs smoothly when testing the project locally across all browsers (including IE11 and Chrome), a hiccup arises once the project is ...

Encountering obstacles when trying to implement mongoose virtuals in a TypeScript environment

I have been exploring how to utilize virtuals in mongoose with typescript. Let's say I have an interface for defining a user. interface User { id: mongoose.ObjectId; name: string; likes: string; } Next, I define a schema for mongoose. // ...

`Bootstrap 4 fails to center elements vertically`

Struggling to center a panel using Bootstrap 4? Despite adding classes like align-items-center and h-100, the header continues to stay at the top of the page. Does anyone know the solution? This is in an Angular 4 project with Bootstrap. <div class=&ap ...

Retrieve select options only upon clicking

Essentially, I have a default value that needs to be loaded into a select element and then make an API call to load the rest only when the select is clicked. <select (click)="getSubevents(market_uri)"> <option *ngFor="let subeven ...

Unlimited requests sent to the server while subscribing to an observable on HTTP

I am currently enhancing an Angular2 website with a feature to display the name of the user who is logged in. While I have been successful in retrieving the necessary information from the back-end service, I am encountering an issue where requests are sen ...

Facing issues updating the parent state value while using NextJs with React

I recently started working with NextJS and React, and I'm using trpc along with useQuery to fetch a list of users. After fetching the user list, I need to filter it based on the user's name. Below is a snippet of the code I've been working ...

Leverage a unified custom theme across both iOS and Android platforms in Ionic 3

My Ionic application displays distinct widgets for the iOS and Android platforms. What is the most effective method to maintain customized buttons, input boxes, etc., that are consistent across both platforms? How can I create a unified theme for all plat ...

The *ngIf directive is refusing to display a template

I am currently facing an issue with my .html file where I am trying to display values based on a condition using "*ngIf". The condition is to find a value that ends with "Rechercher ...", but I am having trouble getting it to work. I have tried various app ...

The Angular build process was successful on a local machine, however, the Angular build failed when

I am facing a challenge with my Angular project that I want to deploy on Gitlab Pages. Initially, when I execute: ng build --prod locally, the build is successful. Below is my .gitlab-ci.yaml: image: node:8.12.0 pages: cache: paths: - node_mo ...

Is it possible to set up Injector within TestBed?

Currently, I am in the process of writing test cases for a custom ErrorHandler within Angular. In my implementation, I have included Injector as a dependency in the constructor due to the understanding that providers are initialized after ErrorHandler. The ...

Utilizing TypeScript: Importing a typed module within a d.ts file (from an npm package)

I am currently working on integrating a definition file into an npm package that has dependencies on React. The specific library in question can be found at https://github.com/eiriklv/react-masonry-component. In my TypeScript project, I have successfully ...

Can you identify the specific error type that occurs in the onError function of react-query's MutationCache when using Typescript

Can someone help me with identifying the type of error in react-query MutationCache onError function when using Typescript? I also need guidance on how to override the type so that I can access and use the fullMessage from the data. const queryClient = new ...

What is the purpose of using both forRoot() and forChild() in the RouterModule

What is the purpose of Angular RouterModule using forRoot() and forChild() methods? I recently learned about the forRoot pattern and how it protects provider singletons from being imported multiple times (https://angular.io/guide/singleton-services#the-fo ...

Address the NPM alert regarding Bootstrap's 'unmet peer dependency' in Angular even if Bootstrap is not utilized

In my web project, I am using Angular 5.2.0 along with Bootstrap 4. To install Bootstrap 4, I used the command npm i bootstrap --save, which resulted in unmet peer dependencies warnings: npm WARN <a href="/cdn-cgi/l/email-protection" class="__cf_email_ ...

Is it possible to enlarge the panel only by clicking on the text, without affecting the entire header panel?

I need help with my accordion setup. I want to be able to expand or collapse each panel by clicking only on the header text, not the entire header area. Can anyone provide guidance on how to achieve this? For example, when I click on the text for 'He ...

Issue with Angular2 input not firing the change event

I am facing an issue where the (change) event is not triggered when updating an input field that is being updated from a query. Here is the HTML code for the input: <input type="text" [ngModel]="inputValue" id="itemText" (ngModelChange)="setNewItem($e ...

Issues with the ionViewDidLoad() function?

Having some trouble implementing Email Authentication in my project. The method ionViewDidLoad is not being recognized. I also tried using the method ionViewWillLoad() but that didn't work either. Any ideas on what might be causing this issue? Here&a ...

The flatMap function is not operating as intended in the sequence of function calls

Having difficulty organizing a chain of calls using TypeScript with RxJS observables I am new to RXJS and I am struggling to structure a chain of calls in my TypeScript code. My question is - how can I ensure that this.http.get(''); is only cal ...

How to send variables to a function when a value changes in TypeScript and Angular

As someone who is new to Angular and HTML, I am seeking assistance with the following code snippet: <mat-form-field> <mat-select (valueChange)="changeStatus(list.name, card.name)"> <mat-option *ngFor="let i of lists"> {{i.name}} ...

Implementing TypeScript type definitions for decorator middleware strategies

Node middlewares across various frameworks are something I am currently pondering. These middlewares typically enhance a request or response object by adding properties that can be utilized by subsequent registered middlewares. However, a disadvantage of ...