Iterate over JSON object instead of an array


#1

this is the pastebin for the json:
https://pastebin.com/k62B97sv

i am using this code:
home.html:

<div *ngFor="let item of details.Items">
    <p>{{item.Item.ASIN}}</p>
  </div>

home.ts:

 public productID:any;
  public details:any={};
  constructor(public navCtrl: NavController,public http: Http ,public navParams: NavParams) {
    this.http.get('http://localhost/testApp/dev/item_lookup.php?pid=B014DYVWWS')
             .subscribe(res => {this.details = res.json(); console.log(this.details)});
   
  }

i am receiving no errors here.

can anyone help here…please need it quick


#2

I have no idea what you’re expecting to happen, but you’re iterating over an array that has one element.


#3

trying to get the ASIN property of the Item…
can you tell how to access it?


#4

There isn’t really anything to iterate over here.

{{details.Items.Item.ASIN}}


#5

Now showing this error:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'Item' of undefined
TypeError: Cannot read property 'Item' of undefined
    at Object.eval [as updateRenderer] (ProdDetails.html:19)

on doing this:
{{details.Items.Item.ASIN}}


#6

As I said in the other thread mere minutes ago, if you’re getting this stuff from futures, you have to initialize things in the template to sane enough defaults. In the long run, I think you are trying to push too much work into the template. I would do this instead:

item = {};

http.get(url).subscribe((rsp) => {
  let raw = rsp.json();
  this.item = raw.Items.Item;
});

<p>{{item.ASIN}}</p>

#7

still…on console its showing the value but not in html view…


#8

WFM, so I don’t know what else to say.

details = {/*your pastebin*/};
item = {};
constructor() {
  Observable.of(this.details)
  .delay(2000)
  .subscribe(deets => this.item = deets.Items.Item);
}
<p>{{item.ASIN}}</p>

2 seconds elapse, B014DYVWWS appears in HTML.


#9

still nt working…
there is some issue with subscribe …the control is not coming out of it i think…console.log for everything is working fine inside the subscribe…but not outside
the code of line just after subscribe is not working…


#10

That is how asynchronous programming works. Inside the subscription is the only place you can rely on the data. If you assign it to an object property from there, Angular’s change detection is smart enough to do the right thing and reflect the changes in the template.