3

I have a service and inside the constructor I am running a method to get some data. I can see the data so then I pass it to a pre-defined variable.

Like this:

export class SentinelService {

  configuration;

  constructor() {


    this.electronService.ipcRenderer.on('config' , function(event , data) {

      this.configuration = data; // pass the data to configuration variable

      console.log(this.configuration.name); // Check it ... I can see the value here


    });

  }


  myMethod() {

    // Try it here
    console.log(this.configuration.name); // I get Undefined

  };


  ...

Although I have assigned the value to 'configuration' variable and can see that it's been passed from the method inside the constructor, when I try the same thing on another method I get undefined.

How can I fix this?

1 Answers1

5

Use an arrow function as your callback to keep the class scope:

this.electronService.ipcRenderer.on('config' , (event , data) => {
  this.configuration = data; 
  ...

Also, have a look at this to understand why normal functions and arrow functions are different.

bugs
  • 14,631
  • 5
  • 48
  • 52