首页 > 解决方案 > 如何使用 ngFor 通过 http 服务接收数据?

问题描述

我试图将服务(contact.service.ts)注入组件(contact-list.component)我试图提供给组件的服务(或数据)是员工的详细信息(在contacts.ts中定义)。我成功接收到数据,但无法使用 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);

  }

}

这是我尝试渲染的内容

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

并导致此错误

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

标签: angulartypescriptinterfacehttpservice

解决方案


查看来自 API 的数据:它不是数组,而是包含数组的对象。因此你应该

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

推荐阅读