【问题标题】:Angular 7 Component Observable Named vs Anonymous functionAngular 7 Component Observable Named vs Anonymous 函数
【发布时间】:2018-12-10 23:36:00
【问题描述】:

我创建了一个 Angular 7 组件,该组件具有来自 Angular 服务的 observable。我正在使用它将来自远程服务的数据绑定到我的一个页面上的列表。它工作得很好。但是,我注意到的一件事是在订阅异步回调中,如果我使用命名函数而不是匿名函数,则数据不会绑定到我页面上的列表。

这是当前有效的匿名回调示例

public constructor(private vendorApiService: VendorApiService,
    private eventMessagingService: EventMessagingService) {

    this.vendorApiService.getVendors().subscribe(
      (data) => {
        this._vendor = data;
        this.dataSource = new MatTableDataSource<Vendor>(this._vendor);
        this.dataSource.paginator = this.paginator;
      });
    this._displayedColumns = ['id', 'code', 'name', 'edit'];
}

我想把它转换成这个。但是,这不起作用:

public constructor(private vendorApiService: VendorApiService,
  private eventMessagingService: EventMessagingService) {

    this.vendorApiService.getVendors().subscribe(
      this.setup_vendor_list);
    this._displayedColumns = ['id', 'code', 'name', 'edit'];
}

private setup_vendor_list(data) {
  this._vendor = data;
  this.dataSource = new MatTableDataSource<Vendor>(this._vendor);
  this.dataSource.paginator = this.paginator;
}

根据我对 Javascript 的了解,这应该可行。但是,由于这是打字稿,可能有一些我不知道的特殊情况会影响命名和匿名回调的处理方式。

如果您能解释差异,请这样做。

【问题讨论】:

  • 你在第二种情况下得到了什么?
  • 添加console.log 并尝试在您的函数中记录this。箭头函数不会改变this 的值,但命名函数会。这可能是它不起作用的原因。但是,您可以传递一个调用您的函数的箭头函数,如(data) =&gt; setup_vendor_list(data)

标签: angular typescript callback observable angular7


【解决方案1】:

这与 TypeScript 无关,它仍然是纯 JavaScript 问题。将this.setup_vendor_list 作为参数传递与传递相同

function (...args) { return this.setup_vendor_list(...args) },

一样
(...args) => this.setup_vendor_list(...args),

你似乎相信。

这也与命名函数和匿名函数无关:请注意我的两个示例都是匿名的。然而,只有一个是箭头函数

影响您的区别在于this 在这些函数中的解析方式,您可以在How does the "this" keyword work? 中了解更多信息。


两种最快的解决方法:

subscribe(this.setup_vendor_list.bind(this))
subscribe(data => this._setup_vendor_list(data))

【讨论】:

  • 是的,你对“这个”是正确的。我应该意识到这一点。我有时会忘记“这个”上下文。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-10
  • 1970-01-01
  • 2021-07-06
  • 2016-05-07
  • 2019-10-15
  • 2019-07-05
相关资源
最近更新 更多