John Baxter John Baxter - 10 months ago 74
Javascript Question

Angular 4 display data that is in this

I do not like the data that is coming back from an API to my angular 4 application.

Here is an example of the JSON , I don't care anything about the USD, but this is the type of data that I'm dealing with

End goal is to display on the page

Coin Price

BTC $4,281.28
ETH $294.62
etc..


JSON

{
"BTC": {
"USD": 4281.28
},
"ETH": {
"USD": 294.62
},
"LTC": {
"USD": 43.4
},
"EOS": {
"USD": 1.7
},
"DASH": {
"USD": 197.69
}
}


Service file

getAllCoins(): Observable<Response> {
return this.http.get(this._url)
.map(res => res.json())
.do(data => console.log('coins ' + JSON.stringify(data)))
.catch(this.handleError)

}


Component file that subscribes to coinService

this.coinService.getAllCoins()
.subscribe(
(data) => {
for (let key in data) {
this.coinsList.push(data[key]);
console.log('key', key)
}
},
(error) => console.log("error : " + error)

);


Finally then the template html

<div *ngFor="let coin of coinsList">
<span>{{coin | json}}</span>
</div>


I can see that
key
will display BTC etc.. in console.log
and then on the page I see

{ "USD": 4234.31 }


But I don't want to see brackets and all that , but instead coin (BTC) and Price -

Should I push different data into my array ?
coinsList = [];

Answer Source

Please update your code like below :

this.coinService.getAllCoins()
        .subscribe(
        (data) => {
            for (let key in data) {
               this.coinsList.push({coinName:key,price:data[key].USD}); //change is here
                console.log('key', key)
            }
        },
        (error) => console.log("error : " + error)

        );

and in View

<div *ngFor="let coin of coinsList"> <span>{{coin.coinName}} {{coin.price}}</span> </div>

This should yield your desire result.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download