Search code examples
arraysangularpushngoninit

pushed Array undefined on ngAfterViewinit


i have pushed some values on an Array on Angular ngOnInit and data became unusable on ngAfterViewInit, It shows the particular value as Undefined

randomNUMber = [];

 ngOnInit() {

this.apiServices.getLineChart(this.coinId).subscribe(resc => {

          for (let i =0 ; i < 8 ; i++) {
            this.randomNUMber.push(Number(resc.data[i].price));
          }

          console.log('price1', this.randomNUMber[2]); //it Works
        });

}

ngAfterViewInit() {
console.log('price1', this.randomNUMber);  //this Wors too
console.log('price1', this.randomNUMber[2]); // But this doesnt work 
}

Solution

  • ngOnInit() does not wait for async calls so you could do like :

    ...
    this.myObs$: Observable<any>;
    
    ngOnInit() {
       this.myObs$ = this.apiServices.getLineChart(this.coinId).pipe(map(resc => {
          let randomNUMber: number[] = [];
          for (let i =0 ; i < 8 ; i++) {
             randomNUMber.push(Number(resc.data[i].price));
          }
    
          return randomNUMber;
        }));
     }
    

    If you use ngAfterViewInit, I guess you need to display this data correctly on your template. So you need to use the async pipe to subscribe to this.myObs$

    <div *ngIf="(myObs$ | async) as randomNUMber">
       <p *ngFor="let number of randomNUMber">
        {{ number }}
       </p>
    </div>
    

    See Async pipe