0

I have component in my angular 5 project, bill-page. On bill-page I get some info, bill and currency. It is two arrays, bill (array with one object, get it from my firebase) and currency (array with two objects, get it from free api). When I wanna chek this arrays by using

console.log() 

it shows me that is two normal arrays with some objects.

  export class BillPageComponent implements OnInit {
    currency: any = [];
    bill: any = [];
    userId: string;
    isLoaded = false;
    copyCurrency: any = [];

  constructor(private billService: BillService, private authService: AuthService) {}

  ngOnInit() {
    this.isLoaded = false;
    this.userId = this.authService.returnAuthState();
    this.billService.getBillFirebase(this.userId).subscribe(
    (resp)=>{ 
      for (let key in resp) {this.bill.push(resp[key])}
    }
  );
  console.log(this.bill);//[{currency: "USD", value: 0}]

  this.billService.getCurrencyPB().subscribe((data)=>{
    this.currency.push(data[0]);
    this.currency.push(data[1]);
  });
  console.log(this.currency); //[{key1:1, key2:2},{key3:3, key4:4}]
  this.isLoaded = true;
  }

But when I try get this objects from arrays, or property from objects it becomes undefined, for example

console.log(this.bill[0])// undefined or console.log(this.bill[0].value)//undefined

or if I try copy this arrays it becomes undefined too

this.copyCurrency = this.currency.slice();
console.log(this.copyCurrency) // undefined 
Kos
  • 13
  • 3

1 Answers1

0

Basically what happened was that it executed aysnchronously. console.log (this.bill) executed before it got any value. this.bill gets the value only inside the subscribe function.

Franklin Pious
  • 3,670
  • 3
  • 26
  • 30
  • Yes, you right, problem was that I need this two arrays in my child component, which should rendered only after this two subscription functions are done, and I have only one flag `isLoaded` out of any subscription functions, thats why I should combine two subscription functions or use two flags in that functions, thanks for helping – Kos May 20 '18 at 13:37