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 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.