Angular 4 , 'this' is undefined when using callback 'onComponentInitFunction' function of ng2-smart table

荒凉一梦 提交于 2019-12-11 03:52:16

问题


I am using ng2-smart-table in my component.

I am trying to invoke the parent component's approveTheOrder() method but I am unable to get the object of the parent class

Below is the snippet

{
  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
};

Does anyone have any idea how to get the 'this' in the below onComponentInitFunction() ?

Below is the image of the error that I am getting.

Also I tried to use 'bind' function was unsuccessful in achieving the goal, Could anyone please guide me here, I am really stuck at this point.

EDIT 1 Note that I am able to get event from ChildComponent in the parentComponent, but the problem here is specific to ng2-smart-table component.

To get the value from ChildComponent, I am trying to use in-build callback function onComponentInitFunction(instance) of ng2-smart-table component


回答1:


The following syntax:

{
  onComponentInitFunction(instance) {
    ...

will be transformed to function expression:

{
  onComponentInitFunction: function(instance) {
    ...

You should use arrow function to retain this:

onComponentInitFunction: (instance) => {


来源:https://stackoverflow.com/questions/46613256/angular-4-this-is-undefined-when-using-callback-oncomponentinitfunction-fu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!