简体   繁体   中英

List users with Angular Rest-APi reqres

I am trying to list users from a REST-API reqres. but when I click the button to list users, I get

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays. 

I can list users in console but not in page. I read that last Angular version does not read map function and I do not know why I am getting this error.

This is my users.component.ts file:

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

}

And this is my users.component.html file:

<button (click)="getUsers()">list users</button>
<div *ngFor="let user of users">
    {{ user | json }}
</div>

this.http.get() returns an Observable. When you assign this.users = this.http.get() , the users object will be an Observable and ngFor won't be able to iterate over it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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