[英]Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.[Angular 8]
I'm trying to Get array data from the following API: http://dradiobeats.x10host.com/api/areas我正在尝试从以下 API 获取数组数据: http : //dradiobeats.x10host.com/api/areas
API应用程序接口
My app.component.ts:我的 app.component.ts:
import { Component, OnInit } from "@angular/core"; import { User } from "./users.model"; import { UsersService } from "./users.service"; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) export class AppComponent implements OnInit { users$: User[]; constructor(private userService: UsersService) {} ngOnInit() { return this.userService.getUsers().subscribe(Data => (this.users$ = Data)); } }
app.component.html: app.component.html:
<div *ngFor="let users of users$"> <p>{{ users.name }}</p> </div>
user.service.ts:用户服务.ts:
import { Injectable } from "@angular/core"; import { HttpClient } from "@angular/common/http"; import { User } from "./users.model"; @Injectable({ providedIn: "root" }) export class UsersService { apiUrl = "http://dradiobeats.x10host.com/api/areas"; constructor(private _http: HttpClient) {} getUsers() { return this._http.get<User[]>(this.apiUrl); } }
user.model.ts:用户模型.ts:
export class User { name: string; description: string; domain: string; }
Thanks.谢谢。
The API has returned an object containing your data, rather than an array. API 返回了一个包含您的数据的对象,而不是一个数组。 If you console.log() (or look at the link you posted) the result of the API call you will see that it probably has another element inside that is an array eg如果您使用 console.log() (或查看您发布的链接)API 调用的结果,您将看到它内部可能有另一个元素,即数组,例如
{
data: [... list of items...]
}
So you just need to change the line of code to be:所以你只需要将代码行更改为:
return this.userService.getUsers().subscribe(Data => (this.users$ = Data.data));
为users$
分配一个空数组,如下所示:
users$: User[] = [];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.