列出具有Angular Rest-APi要求的用户

时间:2018-06-19 15:57:56

标签: rest api

我正在尝试从REST-API要求中列出用户。但是当我单击按钮列出用户时,我得到

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>

1 个答案:

答案 0 :(得分:0)

this.http.get()返回一个Observable。当您分配this.users = this.http.get()时,users对象将是一个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
  });
}