Angular 6 - 将数据传递到 class 变量时未定义
Angular 6 - getting undefined when passing data into class variable
我有一个服务,在构造函数中我是 运行 获取一些数据的方法。
我可以看到数据,然后将其传递给预定义的变量。
像这样:
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
};
...
虽然我已将值赋给 'configuration' 变量并且可以看到它是从构造函数内部的方法传递的,但是当我在另一个方法上尝试同样的事情时我得到了未定义。
我该如何解决这个问题?
使用箭头函数作为回调以保持 class 范围:
this.electronService.ipcRenderer.on('config' , (event , data) => {
this.configuration = data;
...
此外,请查看 以了解为什么普通函数和箭头函数不同。
我有一个服务,在构造函数中我是 运行 获取一些数据的方法。 我可以看到数据,然后将其传递给预定义的变量。
像这样:
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
};
...
虽然我已将值赋给 'configuration' 变量并且可以看到它是从构造函数内部的方法传递的,但是当我在另一个方法上尝试同样的事情时我得到了未定义。
我该如何解决这个问题?
使用箭头函数作为回调以保持 class 范围:
this.electronService.ipcRenderer.on('config' , (event , data) => {
this.configuration = data;
...
此外,请查看