Home > database >  ngFor Json Object not displaying desired values
ngFor Json Object not displaying desired values

Time:11-17

I'm trying to make a rest call and then display the get results.

I've done it successfully with a simpler json data structure/object, but not able to get ngFor to work with this particular data structure, I've tried a few combinations of pipe and slice, not converting the result to an array, etc. but still not able to access the data under "items", hoping someone can help me out, I've already spent a few hours trying to figure it out!

The get call is working, here's how it is implemented:

   wishlist: any = [];
    url: string = 'xxx'
  
    getWishlist(){
      this.http.get(this.url,this.httpOptions).subscribe((wishlist: any)=>{
        this.wishlist = wishlist;
        this.wishlist = Array.of(this.wishlist);
        console.log(wishlist);
      });
    }

The simple ngfor that compiles but doesn't work (just shows the name, year,etc. with no value) (I know it's incomplete):

 <div *ngFor="let wishlist of wishlist">
    <h1>name ~ {{wishlist.name}}</h1>
    <h1>year ~ {{wishlist.year}}</h1>
    <h1>country ~ {{wishlist.country}}</h1>
</div>

The reason the get call works but I'm just not able to properly parse and display the data is because I see a success using the dev tools and can see the data retrieved there, the data structure of the json object is my problem (that items parent tag is what is giving me a hard time I think, i have other calls working when that isnt present):

{
    "items": [
        {
            "id": 1,
            "name": "Gold American Eagle",
            "year": "1977",
            "country": "USA",
            "links": [
                {
                    "rel": "self",
                    "href": 
                }
            ]
        },
        {
            "id": 2,
            "name": "Gold Mapple Leaf",
            "year": "1973",
            "country": "CANADA",
            "links": [
                {
                    "rel": "self",
                    "href": 
                }
            ]
        },
        {
            "id": 99,
            "name": "Gold Buffalo",
            "year": "1975",
            "country": "USA",
            "links": [
                {
                    "rel": "self",
                    "href": 
                }
            ]
        },
etc.

Dev Tools: enter image description here

I tried slice, pipe, not converting the result to an array on the rest call, etc. I am expecting the values of the rest call to show up, but just get empty rows:

enter image description here

CodePudding user response:

Maybe you need this:

 <div *ngFor="let item of wishlist?.items">
    <h1>name ~ {{item.name}}</h1>
    <h1>year ~ {{item.year}}</h1>
    <h1>country ~ {{item.country}}</h1>
</div>
  • Related