Angular 6-将数据传递到类变量时变得不确定

Pau*_*l B 2 typescript angular angular6

我有一个服务,在构造函数中,我正在运行一种方法来获取一些数据。我可以看到数据,然后将其传递给预定义的变量。

像这样:

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

  };


  ...
Run Code Online (Sandbox Code Playgroud)

尽管我已经将值分配给“ configuration”变量,并且可以看到它是从构造函数内部的方法传递的,但是当我在另一个方法上尝试相同的操作时,却无法定义。

我怎样才能解决这个问题?

bug*_*ugs 5

使用箭头函数作为回调以保持类范围:

this.electronService.ipcRenderer.on('config' , (event , data) => {
  this.configuration = data; 
  ...
Run Code Online (Sandbox Code Playgroud)

另外,请查看此内容以了解正常功能和箭头功能为何不同。