Home > OS >  Using 'this' inside of an observer callback [duplicate]
Using 'this' inside of an observer callback [duplicate]

Time:09-22

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.

CodePudding user response:

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);
  }
});
  • Related