【问题标题】:Using 'this' inside of an observer callback [duplicate]在观察者回调中使用“this”[重复]
【发布时间】:2021-11-16 00:21:35
【问题描述】:

我有一个刚刚从 v8 更新到 v12 的 Angular 应用程序。

我处理对可观察对象的响应的方式现在已弃用,虽然我更改了代码,但“this”在回调中不再有效,我想知道解决这个问题的最佳方法是什么?

这就是我过去处理 observables 的方式;

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

我已经改成这个了;

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

由于代码不再使用箭头函数,this 不再引用父类,因此我无法再访问该父类的属性和方法。

有没有办法解决这个问题,还是我必须在回调之外创建一个引用 this 的变量?

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

这似乎有点乱。

【问题讨论】:

  • 它们仍然可以是箭头函数:this._trialService.currentTrial().subscribe({ next: trial => { this.trial = trial; this.loadVisitDetails() }, error: error => { this._alertService.showWarningAlert(error.error.title); } });
  • 使用:subscribe({next: (trial) => { ... }, error: (error) => { ... }, complete: () => { ... });
  • 你有关于弃用的参考吗?我在the docs 中没有看到任何内容。我看到您可以按照您指定的第二种方式进行操作,但我没有看到第一种方式的弃用通知。
  • 关于弃用的信息:stackoverflow.com/a/55472361/6513921

标签: javascript angular typescript


【解决方案1】:

您仍然可以为处理程序使用箭头函数:

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

【讨论】:

    猜你喜欢
    • 2010-12-04
    • 1970-01-01
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 2021-11-06
    • 1970-01-01
    相关资源
    最近更新 更多