Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

280
Views
Got undefined when accessing variables that are initialized outside of subscribe

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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);

  }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!