Angular 4 , 'this' is undefined when using

2019-07-14 06:12发布

问题:

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) => {