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>