【问题标题】:How to call service from ag-grid valueFormatter如何从 ag-grid valueFormatter 调用服务
【发布时间】:2020-04-20 18:17:36
【问题描述】:

有谁知道如何在Angular2+中从ag-grid的ValueFormatter调用服务?

例子:

我在构造函数中注入了一个名为 someService 的服务,并希望从 ValueFormatter 调用该服务。我应该怎么做才能做到这一点?

constructor(private service: SomeService) { }

this.columnDefs.push(
        {
            headerName: 'Date',
            width: 150,
            field: 'incidentDate',
            valueFormatter(params) {
                return this.service.doSomething(params.value);
            }
        });

目前,它无法识别来自 valueFormatter 的服务。

提前致谢

【问题讨论】:

  • return this.service.doSomething(params.value); 表示您使用 this 作为对 ag-grid 组件的引用,而不是对托管组件的引用。因此,您需要在组件中使用新的私有函数封装逻辑,并且应该使用this 来引用您的托管组件及其注入的服务。

标签: angular typescript ag-grid


【解决方案1】:

我找到了解决问题的方法。我只需要执行以下操作:

 this.columnDefs.push(
    {
        headerName: 'Date',
        width: 150,
        field: 'incidentDate',
        valueFormatter: this.anotherFunction.bind(this)
    });

anotherFunction(params): string {
    return this.service.doSomething(params.value);
}

【讨论】:

  • 如您所见,this 不是您的组件。另一种选择是:valueFormatter: (params) => this.anotherFunction(params).
  • @GruffBunny 你是我的英雄。绑定看起来很丑。
【解决方案2】:

您错过了从构造函数创建的someService 实例的引用。这可以通过使用 this 关键字来解决。试试下面的代码

valueFormatter(params) {
   return this.service.doSomething(params.value);
}

【讨论】:

  • 那是我的错字。我忘了放这个。但即使这样,它仍然不起作用。你以前用过 ag-grid 吗?
猜你喜欢
  • 2020-07-09
  • 2020-05-09
  • 2018-09-08
  • 2021-03-25
  • 2018-04-30
  • 2021-01-02
  • 1970-01-01
  • 2022-09-28
  • 2020-03-07
相关资源
最近更新 更多