首页 > 解决方案 > 在 ngFor 的帮助下迭代 Angular5 中的 JSON 数组

问题描述

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

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

}

我的 component.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": "" }] } }

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

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 数组。

标签: arraysjsonangulartypescriptangular5

解决方案


你应该在你的 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;
  });

希望这对你有帮助!!!


推荐阅读