【问题标题】:method VS () => method() - Angular 2 done() callback function subscribe Observable RxJSmethod VS () => method() - Angular 2 done() 回调函数订阅 Observable RxJS
【发布时间】:2016-12-23 19:54:38
【问题描述】:

我对使用 RxJS 时 subscribe() 方法中的 done 函数有疑问。

我的应用程序有一个代码:

ngOnInit() {
  this._dictionaryService.loadDictionary()
  .subscribe(
    dictionary => this.dictionary = dictionary,
    error => this.errorMessage = <any>error,
    this.loadQuestion);
}

它不起作用。 但是如果改变

this.loadQuestion);

到

() => this.loadQuestion());

一切正常。

所以,这段代码:

ngOnInit() {
  this._dictionaryService.loadDictionary()
  .subscribe(
    dictionary => this.dictionary = dictionary,
    error => this.errorMessage = <any>error,
    () => this.loadQuestion());
}

效果很好。

this._dictionaryService.loadDictionary() 从文件中获取 JSON 数据。

this.dictionary 是一个类属性。 当我尝试在第一个示例中评估此属性时,我得到一个未定义的。 但在 2ns 示例中一切正常。

所以,它有效,但我不明白其中的区别。我不明白为什么 1s 的例子不起作用。

有人可以解释一下吗?

【问题讨论】:

标签: angular typescript rxjs observable subscribe


【解决方案1】:

这是因为当您编写 this.loadQuestion 时,您传递了对函数 loadQuestion 的引用,但您将丢失 this 上下文。当您使用箭头函数时,this 上下文将被保留。

您也可以编写this.loadQuestion.bind(this) 来获取loadQuestion 函数,并将this 上下文固定为当前上下文。

【讨论】:

    猜你喜欢
    • 2016-12-12
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    • 2018-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多