在 ngFor 的帮助下迭代 Angular5 中的 JSON 数组



我正在使用Angular5来构建一个项目。我被困在*ngFor. 我有一个模型类如下:

export class FetchApi {
value: Array<String>;
api_status: string;
api_version: string;
data: Array<String>;
}

我的组件.ts正在从服务接收数据,该服务正在调用API并获取数据。

我的服务代码是:

public getUsers() { 
console.log("heyyy"+this.fetchUrl);
return this.http.get <FetchApi[]> (this.fetchUrl); }

我的组件代码是:

ngOnInit() {
const scope = this;
this.userService.getUsers()
.subscribe( data => {
this.fetchApi = of(data);
console.log(this.fetchApi)
//this.fetchApi = data;
});
};

API 返回的 JSON 是这样的:

{ "api_status": "200", "api_version": "1.0", "data": { "featured": [{ "id": 1, "vid": "", "uid": , "title": "", "description": "" }] } }

我想在<tr *ngFor="let fetch-api of fetchApi ">的帮助下在我的 HTML 页面上呈现响应,但是收到错误:

FetchApiComponent.html:22 ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays. at NgForOf.push../node_modules/@angular/common/fesm5/common.js.NgForOf.ngOnChanges (common.js:3121) at checkAndUpdateDirectiveInline (core.js:8941) at checkAndUpdateNodeInline (core.js:10209) at checkAndUpdateNode (core.js:10171) at debugCheckAndUpdateNode (core.js:10804) at debugCheckDirectivesFn (core.js:10764) at Object.eval [as updateDirectives] (FetchApiComponent.html:22) at Object.debugUpdateDirectives [as updateDirectives] (core.js:10756) at checkAndUpdateView (core.js:10153) at callViewAction (core.js:10394)

请让我知道我做错了什么,因为我是 Angular5 的新手。如何在我的 HTML 页面上获取我的 JSON 数组。

你应该在你的 html 中这样做来处理 html 中的错误

<tr *ngFor="let fetch-api of fetchApi?.data?.featured">

在您的打字稿中,例如:

this.userService.getUsers()
.subscribe((data) => {
this.fetchApi = data;
console.log(this.fetchApi)
//this.fetchApi = data;
});

希望这对您有所帮助!!

你应该写

<tr *ngFor="let fetchApi of fetchApi.data.featured">

以及 For/循环应该在数组中执行,fetchApi 是对象

然后你可以像下面这样显示你的数组的json。

<tr *ngFor="let fetchApi of fetchApi.data.featured">
<td>{{fetchApi | json}}</td>
</tr>

对于打印 Id,如下所示

<tr *ngFor="let fetchApi of fetchApi.data.featured">
<td>{{fetchApi.id}}</td>
</tr>

最新更新