簡體   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