cglyn_kya
cglyn_kya

Reputation: 33

Angular, Cant reach Object Arrays content

I want to use a crypto coin api and i get data from server to my "_coins:coin[]" list. I tried "Console.log(_coins)" , console shows the array, also I can open this list at html page with "*ngFor" but i cant open at .ts file.

i tried this at component

public _coins:coin[]=[];
  constructor(private _coinrepo:CoinRepository) {
    this._coins=this._coinrepo.getMultiCoins(["BTC","ETH"]);
    console.log(this._coins);
   }

and at console:

Array []​
0: Object { KEY: "BTC", BTC: 1, USD: 10018.38, … }
1: Object { KEY: "ETH", BTC: 0.02072, USD: 207.49, … }
length: 2
<prototype>: Array []

but i tried

public _coins:coin[]=[];
  constructor(private _coinrepo:CoinRepository) {
    this._coins=this._coinrepo.getMultiCoins(["BTC","ETH"]);
    this._coins.forEach(i=>{
      console.log(i);
    });
   }

and at console nothing. I also tried for loop, .find, .pop ... nothing work. i want to take data like :

for(let item of this._coins){
      _btc=item.BTC;
      _usd=item.USD;
    }

Please help me.. codes are here : https://stackblitz.com/edit/angular-ejrojd?embed=1

Upvotes: 3

Views: 88

Answers (2)

user2216584
user2216584

Reputation: 5602

You should not return an array [or subscribe in the service] from the this._coinrepo.getMultiCoins(["BTC","ETH"]), instead you should return an observable and then subscribe in the component. Because this.restService.getMultiCoin(c_list.toString()) is an async call which will not immediately return. Change your method like this:

 getMultiCoins(c_list:string[]): Observable<coin[]>{
    return this.restService.getMultiCoin(c_list.toString())
        .pipe(
          map(apiRes => {

            for (let item in apiRes) {
               this.coins.push(
                { KEY: item, BTC: apiRes[item].BTC, USD: apiRes[item].USD, EUR: apiRes[item].EUR, TRY: apiRes[item].TRY }
            )
        }                
            return this.coins;
          })
        )
 }

Now in you component subscribe to the Observable returned from getMultiCoins API to unwrap the coins array like this:

public _coins:coin[]=[];
  constructor(private _coinrepo:CoinRepository) {
    this._coinrepo.getMultiCoins(["BTC","ETH"]).subscribe((coins) => {
      this._coins = coins;
        this._coins.forEach(i=>{
        console.log(i);
      });
     }
    );        
   }

Hope it helps.

Upvotes: 2

ilyas shabi
ilyas shabi

Reputation: 194

It's an Object you can't iterate it using for loop or forEach, try this code:

for(const key in this._coins){
     console.log("key : ", key , " val : ", this._coins[key]);
}

Upvotes: 0

Related Questions