Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular, Cant reach Object Arrays content

Tags:

angular

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

like image 244
cglyn_kya Avatar asked Dec 22 '25 16:12

cglyn_kya


1 Answers

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.

like image 95
user2216584 Avatar answered Dec 24 '25 10:12

user2216584



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!