1

I have a graph.component.ts

this.cContainer = cytoscape ( {  
    ready: function(e) { 
      this._dataService.setResultData();
    }
  });

but I get ERROR TypeError: Cannot read property 'setResultData' of undefined

..so this seems to be unknown, which looks correct because I am within a callback and so this is referred to the ready-callback.

but how would I call _dataService.setResultData() from inside this ready()-callback?

Mka24
  • 369
  • 1
  • 3
  • 8

2 Answers2

3

Use an arrow function to capture this from the declaring context. For function this is determined by the caller and will probably not be your class:

this.cContainer = cytoscape ( {  
    ready: (e) => { 
      this._dataService.setResultData();
    }
  });
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
1

There is a difference regarding this between functions and fat-arrow ES6 functions. The latter version doesn't loose this. So instead of the current function you can use

ready: e => this._dataService.setResultData();

Edit: it could also be ready: function(e) { this._dataService.setResultData(); }.bind(this)

but it is just ugly...

erosb
  • 2,943
  • 15
  • 22