user9597092
user9597092

Reputation:

Angular 6 - getting undefined when passing data into class variable

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?

Upvotes: 3

Views: 4238

Answers (1)

bugs
bugs

Reputation: 15313

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.

Upvotes: 5

Related Questions