rest - 列出具有 Angular Rest-API reqres 的用户
问题描述
我正在尝试从 REST-API reqres 中列出用户。但是当我单击按钮列出用户时,我得到
Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
我可以在控制台中列出用户,但不能在页面中列出。我读到最后一个 Angular 版本不读取地图功能,我不知道为什么我会收到这个错误。
这是我的users.component.ts
文件:
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map'
@Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: ['./users.component.css'],
})
export class UsersComponent implements OnInit {
users: any;
constructor(private http: HttpClient) {}
ngOnInit() {}
public getUsers() {
this.users = this.http.get('https://reqres.in/api/users')
}
}
这是我的users.component.html
文件:
<button (click)="getUsers()">list users</button>
<div *ngFor="let user of users">
{{ user | json }}
</div>
解决方案
this.http.get()
返回一个 Observable。当您分配this.users = this.http.get()
时,用户对象将是一个 Observable 并且ngFor
将无法对其进行迭代。
ngOnInit() {
this.users = []; // to prevent ngFor to throw while we wait for API to return data
}
public getUsers() {
this.http.get('https://reqres.in/api/users').subscribe(res => {
this.users = res.data;
// data contains actual array of users
});
}
推荐阅读
- python - Python - Flask API - TCP 套接字并发
- powershell - 如何借助powershell命令查找计算机是否已加入特定机构的域
- python - Split a column of a CSV file with a specific delimiter
- docker - 从 docker 安装的 Nextcloud。如何下载和安装自定义应用程序?
- python - Selenium.common.exceptions.NoSuchElementException 错误,即使有显式等待
- firebase - v-on 处理程序中的错误:“auth 不是函数”-Vue js
- python - 用 X 替换列表中 3 的倍数
- python - 从 python 列表中选择添加到特定目标数的所有元素[不是两个和问题]
- python - fastapi.Response() 不返回自定义响应
- javascript - 编译为 javascript 时打字稿忽略行