angular - 如何使用 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.
解决方案
查看来自 API 的数据:它不是数组,而是包含数组的对象。因此你应该
this._contactService.getContacts()
.subscribe(data => this.contacts = data.contactsList);
推荐阅读
- docker - GPU out of memory error just by declaring TF Keras Metrics
- c# - 资源大小的 UWP 构建问题(.PRI 文件问题)
- javascript - 如何在 html 中隐藏我的 Google Maps API 密钥?
- java - Java Find Closest Pair in Dataset 给出 NullPointerException
- javascript - 将域列入白名单 - 处理 URL 中的尾部斜杠
- bash - sed 在 for 循环中迭代时无法读取可执行文件
- slurm - 将“胖”节点划分为多个 Slurm 节点
- angular - 对 ngx-datatable 列使用角度组件
- java - 如何将 Spring Kafka 消费者收到的 JSON 转换为准备保存在银行中的实体?
- python - Django RecursionError:比较超过最大递归深度