2

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 = [];

3 Answers3

3

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.

user1608841
  • 2,455
  • 1
  • 27
  • 40
  • 1
    I would probably also add a filter for currency e.g. `{{coin.coinName}} {{coin.price | currency:'USD':true:'1.2-2'}}` regardless - this is a great answer! – Tom Stickel Aug 17 '17 at 07:13
1

Remove the json pipe

<div *ngFor="let coin of coinsList">
  <span>{{coin}}</span>
</div>
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
1

There are lots of ways to do this. You can also do something like:

html:

<div *ngFor="let coin of coinsList; let i = index;">
      <span>{{keyList[i]}}:  $ {{coin}}</span>
</div>

ts:

for(let key in data){
   this.coinsList.push(data[key]["USD"]);
   this.keyList.push(key);
}

Note: Rahul Naik's Array of object's approach is cleaner in my opinion.

Note2: You can also create a custom pipe.

Plunker: http://plnkr.co/edit/zrzVF8qKl8EvKKp2Qt45?p=preview

eko
  • 39,722
  • 10
  • 72
  • 98