Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

110
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.

7 months 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);
  }
});
7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos