繁体   English   中英

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

[英]List users with Angular Rest-APi reqres

我正在尝试从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>

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM