N Sharma
N Sharma

Reputation: 34497

Iterating the JSON Array in Angular5 with the help of ngFor

I am using Angular5 for building a project. I am stuck in *ngFor. I have a model class as below:

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

}

My component.ts is receiving the data from service, which is calling an API and fetching the data.

My service code is:

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

My component code is:

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

My JSON that the API is returning is like this:

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

I want to render the response on my HTML page with the help of <tr *ngFor="let fetch-api of fetchApi "> , however, getting an error:

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)

Please let me know what I am doing wrong as I am new to Angular5. How can I get my JSON array on my HTML page.

Upvotes: 1

Views: 2092

Answers (2)

Sanoj_V
Sanoj_V

Reputation: 2986

You should do in your html like this to handle error in html

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

In your typescript like :

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

Hope this help you!!!

Upvotes: 3

Arash
Arash

Reputation: 1826

You should write

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

As well as For/loop should execute in array and fetchApi is object

And then you can show you'r array's json like below

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

And for printing Id do like below

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

Upvotes: 0

Related Questions