【问题标题】:Angular 4 , 'this' is undefined when using callback 'onComponentInitFunction' function of ng2-smart tableAngular 4,使用 ng2-smart 表的回调“onComponentInitFunction”函数时未定义“this”
【发布时间】:2018-03-18 16:53:33
【问题描述】:

我在我的组件中使用 ng2-smart-table。

我正在尝试调用父组件的 approveTheOrder() 方法,但是我无法获取父类的对象

下面是sn-p

{
  title: "Actions",
  type: "custom",
  renderComponent: ActionRenderComponent,
  onComponentInitFunction(instance) {
    instance.actionEmitter.subscribe(row => {
      if(row == CONSTANT.STATUS_APPROVE){
        //here 'row' value is from childComponent-ActionRenderComponent,which I am able to get easily in parentComponet 
       this.approveTheOrder(instance.rowData.id); // here this is undefined, 

      }
      if(row == CONSTANT.STATUS_REJECT){
        this.rejectOrder();//this is undefined
      }
      if(row == CONSTANT.STATUS_PENDING){
        this.pendingOrder(); // this is undefined
      }
    });
  },

  filter: false
};

有人知道如何在下面的 onComponentInitFunction() 中获取“this”吗?

下面是我收到的错误图片。

另外我尝试使用'bind'功能未能成功实现目标,谁能在这里指导我,我真的卡在这一点上。

编辑 1 请注意,我可以从 parentComponent 中的 ChildComponent 获取事件,但这里的问题是特定于 ng2-smart-table 组件的。

为了从 ChildComponent 中获取值,我正在尝试使用 ng2-smart-table 组件的内置回调函数 onComponentInitFunction(instance)

【问题讨论】:

  • @Yurzui - 是的,您给定的解决方案对我有用。请随时回答问题,以免其他人被此问题困扰
  • @Z.Bagley - 这个问题是 ng-smart-table 特有的,我可以将 ChildComponent 的值取回到 ParentComponent 的构造函数中。但是问题出现在 onComponentInitFunction() 函数中。
  • 道歉,误解和删除。

标签: angular ng2-smart-table


【解决方案1】:

以下语法:

{
  onComponentInitFunction(instance) {
    ...

将转化为函数表达式:

{
  onComponentInitFunction: function(instance) {
    ...

你应该使用箭头函数来保留this

onComponentInitFunction: (instance) => {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    相关资源
    最近更新 更多