Angular 2 无法在 Observable 回调函数中访问 this。

4

I have the following code:

onLogin(): void {

  this.message = "loading";

  this.api.login("username", "password")

    .subscribe(
      this._processData,
      this._logError,
      //error => { this._logError(error); },
    );

}

private _logError(data) {
  console.log(data);
  this.errorMessage = data.message;
};

当我取消注释带有//error ->的行并注释上面的行时,一切都运作正常。
如果有一个直接调用函数的解决方案会很好。
你有什么想法吗?
2个回答

5
我认为这是与JavaScript和TypeScript中使用this关键字本身有关的问题。请参见此链接:https://github.com/Microsoft/TypeScript/wiki/'this'-in-TypeScript
您可以尝试使用如下所述的bind方法:
onLogin(): void {
  this.message = "loading";

  this.api.login("username", "password")
    .subscribe(
      this._processData.bind(this),
      this._logError.bind(this)
    );
}

private _logError(data) {
  console.log(data);
  this.errorMessage = data.message;
}

希望这可以帮助到你, Thierry

5

当我取消注释时,一切都正常工作

好的,您的 _processData() 方法必须不尝试读取或写入任何组件属性,因为它将没有正确/预期的 this 上下文。使用 .subscribe(this._processData, ...)_processData() 中的 this 上下文将是一个 Subscriber 对象,而不是您的组件。

我建议您对成功和错误回调都使用 箭头函数,以获取“与周围代码相同的词法 this”--即让 this 成为组件:

.subscribe(
  data  => this._processData(data),
  error => this._logError(error),
);

我发现这比使用bind()更干净。

1
我赞同你的观点,马克;-) 我更喜欢使用箭头函数作为订阅回调... - Thierry Templier

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接