Home > Blockchain >  Got undefined when accessing variables that are initialized outside of subscribe
Got undefined when accessing variables that are initialized outside of subscribe

Time:06-05

I'm working with Apex chart and the chart is in the second component. I need to call a function to toggle some series in second component from the first component. I'm able to call that function now but when I try to call the chart inside the subscribe, it's undefined. However if I call that chart in the ngAfterViewInit(), the chart is correct. So could anyone suggest me any ideas to access the chart inside the subscribe?

Second component:

export class DashboardComponent implements OnInit {
  @ViewChild("chart") chart!: ChartComponent;
  constructor(public servic: MainService, private spinner: NgxSpinnerService, private router: Router) {
    this.servic.receiveMessage().subscribe(message => {
      this.toggle(message)
    })
  }
  public toggle(state: string) {
    console.log(this.chart);

  }
}

HTML of the second component: Image for the second component

CodePudding user response:

It is not undefined because it is inside .subscribe(). It is undefined because it is inside the constructor(). This is a run time issue. Move your subscription to OnInit() or AfterViewInit() lifecycle hooks

CodePudding user response:

your service file is getting called later that's why your "message" uder subscribe is undefined, move your service into OnInit() from constructor()..

constructor(public servic: MainService, private spinner: NgxSpinnerService, private router: Router) {}
    ngOnInit(){
    this.servic.receiveMessage().subscribe(message => {
          this.toggle(message)
        })
    }
public toggle(state: string) {
    console.log(this.chart);

  }
  • Related