Rest 列出具有角度静止APi需求的用户
我试图从REST-API请求中列出用户。但是当我点击按钮列出用户时,我得到Rest 列出具有角度静止APi需求的用户,rest,api,Rest,Api,我试图从REST-API请求中列出用户。但是当我点击按钮列出用户时,我得到 Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays. 我可以在控制台中列出用户,但不能在页面中列出。我读到上一个角度版本不读取映射函数,我不知道为什么会出现这个错误 这是我的users.component.ts
Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
我可以在控制台中列出用户,但不能在页面中列出。我读到上一个角度版本不读取映射函数,我不知道为什么会出现这个错误
这是我的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')
}
}
<button (click)="getUsers()">list users</button>
<div *ngFor="let user of users">
{{ user | json }}
</div>
这是我的users.component.html
文件:
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')
}
}
<button (click)="getUsers()">list users</button>
<div *ngFor="let user of users">
{{ user | json }}
</div>
列出用户
{{user | json}}
this.http.get()
返回一个可观察值。当您分配this.users=this.http.get()
时,用户对象将是可观察的,而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
});
}
非常感谢你。成功了!再次感谢您的解释。但还有一个问题:重新启动ng serve后,它给了我一个错误属性“data”在类型“Object”上不存在。我想我用这个来修复它。users=res[“data”];相反,如果我想创建一个与Post使用相同RESTAPI的用户,我必须做什么?您可以使用这个.http.Post(URL,数据)。确保传递api接受的数据