Angular 2 Get Values from Object

15,566

Solution 1

Just do this (in your service class):

GetGoldFromJson() {
  return this.http.get('http://live.alsayg.com/api/v1/gold')
  .map(res => res.json())
}

and consume with (in your component, just inject the above service in the constructor of your component):

GoldData:any;
getGold() {
   service.GetGoldFromJson().subscribe(
    data => {
    this.GoldData=data,
   console.log(this.GoldData);
    }
  );
}

Solution 2

This is an async operation, so as per comments the view is rendered before data has been retrieved, therefore the error is thrown. You can solve this in a couple of ways.

Initialize your object, so that it won't be undefined.

GoldData:any = {}

Use *ngIf, which will prevent the part of of the view to be rendered until there is values in GoldData:

<div *ngIf="GoldData">
   {{GoldData.yourProperty}}
</div>

or safe navigation operator:

{{GoldData?.yourProperty}}
Share:
15,566
Fray
Author by

Fray

Updated on June 04, 2022

Comments

  • Fray
    Fray almost 2 years

    I am trying to get value from a json url, i got this result: Console Result

    How can i extract each item from this object (closePrice, price,updateTime)

    this my code:

    GoldData:any;
    
    GetGoldFromJson() {
      this.http.get('http://live.alsayg.com/api/v1/gold')
      .map(res => res.json())
      .subscribe(
        data => {
        this.GoldData=data,
       console.log(this.GoldData);
        }
      );
    }
    
  • Luka Reeson
    Luka Reeson over 2 years
    What about if you only need specific filed(s) from the response?