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

时间:2018-06-10 06:38:38

标签: arrays json angular typescript angular5

我正在使用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": "" }] } }

我想在<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数组。

2 个答案:

答案 0 :(得分:3)

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

希望这对你有所帮助!

答案 1 :(得分:0)

你应该写

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

同样For / loop应该在数组中执行,fetchApi是 object

然后你可以在下面显示你的数组的json

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

对于打印我喜欢以下

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