1

I'm new to Angular 8 and I am using the following structure to fetch data from http get and I am trying to iterate data using *ngFor. Unfortunately, I am getting the following error.

How to fix the error? Thank you in advance '[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> 
3
  • Are you sure that the data returned by this.studentService.getData("get_students") is an array? The error messages suggests it is actually an object. Commented Jun 30, 2019 at 21:10
  • @UncleDave yes, because students => {console.log(this.students)} will show the json array Commented Jun 30, 2019 at 21:12
  • Could you show a screenshot of the console output? Commented Jun 30, 2019 at 21:13

1 Answer 1

1

Your server response is an object you need to retrieve server response data from it

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

That should work if your server sends actual array if it still keeps complaining you need to convert that response into an array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.