I am working on a Contacts app with Angular 9. I get a list of contacts via the following service:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Contact } from '../models/Contact';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
@Injectable({
providedIn: 'root'
})
export class ContactsListService {
contactsUrl = 'https://randomuser.me/api/?&results=500&inc=name,location,email,cell,picture';
constructor(private http:HttpClient) { }
getContcts():Observable<Contact[]> {
return this.http.get<Contact[]>(`${this.contactsUrl}`);
}
}
The Contacts List component is as follows:
import { Component, OnInit } from '@angular/core';
import { from } from 'rxjs';
import { ContactsListService } from '../../services/contacts-list.service';
import { Contact } from '../../models/Contact';
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
})
export class ListComponent implements OnInit {
contactsList:Contact[];
constructor(private ContactsListService:ContactsListService) { }
ngOnInit(): void {
this.ContactsListService.getContcts().subscribe(contactsList => {
this.contactsList = contactsList;
});
}
}
Trying to iterate the contacts list this way
<ul *ngFor="let contact of contactsList">
<li>{{contact.name.first}}</li>
</ul>
throws the error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays
.
That very likely means contactsList
is not an array.
What am I doing wrong?
console.log(typeof this.contactsList);
returns an object. – Razvan Zamfirthis.contactList
to see the actual content – Ashish Ranjan