0

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.

eko
  • 39,722
  • 10
  • 72
  • 98
SheppardDigital
  • 3,165
  • 8
  • 44
  • 74
  • 1
    They can still be arrow functions: `this._trialService.currentTrial().subscribe({ next: trial => { this.trial = trial; this.loadVisitDetails() }, error: error => { this._alertService.showWarningAlert(error.error.title); } });` – T.J. Crowder Sep 22 '21 at 14:06
  • Use: `subscribe({next: (trial) => { ... }, error: (error) => { ... }, complete: () => { ... });` – ruth Sep 22 '21 at 14:07
  • 1
    Do you have a reference for the deprecation? I don't see anything in [the docs](https://angular.io/api/core/EventEmitter#subscribe). I see that you *can* do it the second way you indicate, but I don't see a deprecation notice for the first. – T.J. Crowder Sep 22 '21 at 14:08
  • 1
    Info about the deprecation: https://stackoverflow.com/a/55472361/6513921 – ruth Sep 22 '21 at 14:10

1 Answers1

3

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);
  }
});
Octavian Mărculescu
  • 4,312
  • 1
  • 16
  • 29