Search code examples
angulartypescriptinterfacehttpservice

how to render data using ngFor received throug http service?


I tried to inject a service(contact.service.ts) into a component(contact-list.component) The service(or data) that i m trying to provide to component is details of employees(defined in contacts.ts). I successfully received the data,but not able to render it using ngFor

---------contacts.ts---------------

export interface Contacts {
  contactsList: Contact[];
}

export interface Contact {
  id: number;
  name: string;
  city: string;
}

------------contact.service.ts-----------

import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { Contacts } from '../models/contacts';

// @Injectable({
//   providedIn: 'root'
// })

export class ContactService {
  url = 'http://www.mocky.io/v2/5c5d880f3200000e11220880';

  constructor(
    private http: HttpClient
  ) { }

  getContacts(): Observable<Contacts> {
    // make http request to the given url and fetch the contacts
   // return of({contactsList: []});
    return this.http.get<Contacts>(this.url);
  }
}

-----------contact-list.component--------------

import { ContactService } from 'src/app/services/contact.service';
import { Contacts } from 'src/app/models/contacts';

@Component({
  selector: 'app-contact-list',
  templateUrl: './contact-list.component.html',
  styleUrls: ['./contact-list.component.css']
})
export class ContactListComponent implements OnInit {

  contacts;
  constructor(
    private _contactService: ContactService
  ) { }

  ngOnInit() {
      this._contactService.getContacts()
    .subscribe(data => this.contacts=data);

  }

}

Here is what i tried to render it

<p class="title"> Contact Applications </p>
<div class="list">
  <p *ngFor="let contact of contacts">
    {{contact.name}}
  </p>
</div>

and resulted with this error

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

Solution

  • Look at the data coming from the API: it's not an array, it's an object containing an array. Therefore you should

    this._contactService.getContacts()
        .subscribe(data => this.contacts = data.contactsList);