首页 > 解决方案 > 列出具有 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>

标签: restapi

解决方案


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
  });
}

推荐阅读