user6824054
user6824054

Reputation:

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

Upvotes: 2

Views: 1168

Answers (3)

eko
eko

Reputation: 40647

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

Upvotes: 1

user1608841
user1608841

Reputation: 2475

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.

Upvotes: 3

Sajeetharan
Sajeetharan

Reputation: 222582

Remove the json pipe

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

Upvotes: 1

Related Questions