Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

273
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda