• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Pruebas Online
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

436
Vistas
Using 'this' inside of an observer callback

I have an Angular application that I've just updated from v8 to v12.

The way I handled responses to observables is now deprecated, and while I have changed my code, 'this' no longer works inside the callback and I'm wondering what is the best approach to solve this?

This is how I used to handle observables;

this._trialService.currentTrial().subscribe(trial => {
  this.trial = trial;
  this.loadVisitDetails()
}, error => {
  this._alertService.showWarningAlert(error.error.title);
});

I have changed it to this;

this._trialService.currentTrial().subscribe({
  next(trial) {
    this.trial = trial;
    this.loadVisitDetails()
  },
  error(error) {
    this._alertService.showWarningAlert(error.error.title);
  }
});

Because the code no longer uses arrow functions, this no longer refers to the parent class so I am no longer able to access properties and methods on that parent class.

Is there a way to get around this, or will I have to create a variable outside of the callback that will refer to this?

const self = this;
this._trialService.currentTrial().subscribe({
  next(trial) {
    self.trial = trial;
    self.loadVisitDetails()
  },
  error(error) {
    self._alertService.showWarningAlert(error.error.title);
  }
});

That just seems a bit messy.

almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can still use arrow functions for the handlers:

this._trialService.currentTrial().subscribe({
  next: (trial) => {
    this.trial = trial;
    this.loadVisitDetails()
  },
  error: (error) => {
    this._alertService.showWarningAlert(error.error.title);
  }
});
almost 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda