Home > front end >  Json array to display in view of angular
Json array to display in view of angular

Time:07-06

I pulled the data from laravel api like this

this.dataService.geData().subscribe(res=>{
      this.contacts=res
    });
I got json array return from Laravel like below and i want to loop this to display in view of angular 14.

    {
    "status":true,
    "contacts":
    [
        {"id":1,"name":"Christopher","email":"[email protected]"},
        {"id":2,"name":"Anthony","email":"[email protected]"},
        {"id":3,"name":"John Lenon","email":"[email protected]"}
    ]   
}

I tried this but it is not displaying anything

<tbody>
        <tr *ngFor="let contact of contacts">
            <td>{{contact.id}}</td>
            <td>{{contact.name}}</td>
            <td>{{contact.email}}</td>
        </tr>
    </tbody>

CodePudding user response:

Your code

this.dataService.geData().subscribe(res=>{
  this.contacts=res
});

store the result (res variable) of the call to the Laravel backend in the contacts variable.

If the answer from laravel is

{
    "status":true,
    "contacts":
    [
        {"id":1,"name":"Christopher","email":"[email protected]"},
        {"id":2,"name":"Anthony","email":"[email protected]"},
        {"id":3,"name":"John Lenon","email":"[email protected]"}
    ]   
}

you are storing the whole answer in the variable contacts (not only the contacts property). So you have two ways to solve this problem. The first solution is storing in the contacts variable the value of the contacts property of the answer as follow:

this.dataService.geData().subscribe(res=>{
   // Change res to res.contacts
   this.contacts = res.contacts;
});

The second way is to save the whole answer in a new variable

this.dataService.geData().subscribe(res=>{
   this.wholeAnswer = res;
});

and change the front end to loop through the contacts inside that variable:

<tbody>
    <!-- looping through wholeAnswer.contacts, not just wholeAnswer -->
    <tr *ngFor="let contact of wholeAnswer.contacts">
        <td>{{contact.id}}</td>
        <td>{{contact.name}}</td>
        <td>{{contact.email}}</td>
    </tr>
</tbody>

CodePudding user response:

As explained in my comment you're not accessing the good variable.

That said I'd recommend a more reactive approach:

public contacts$ = this.dataService.geData().pipe(
  map(res=> res.contacts)
);

and the view:

<tbody>
  <tr *ngFor="let contact of contacts$ | async">
    <td>{{contact.id}}</td>
    <td>{{contact.name}}</td>
    <td>{{contact.email}}</td>
  </tr>
</tbody>
  • Related