[英]'this' is undefined in Angular, XML2JS
export class ServerComponent {
servers:string[];
getString:any;
serversJSON:any;
constructor() {
}
ngOnInit() {
console.log("ngOnInit");
this.getXmlService.getData().subscribe((getString) =>
{
xml2js.parseString(getString, function (err, result) {
this.serverJSON = result; // This doesn't work
console.log(result); // This works
});
});
}
}
In this code, the indicated line does not seem to be able to access this
. 在此代码中,指示的行似乎无法访问
this
。 Console logging shows an undefined
. 控制台日志记录显示
undefined
。 result
gives me a correct and formatted JSON, but when I attempt to take the result
variable and set it in the this.serverJSON
, it throws an error Cannot set property 'serversJSON' of undefined
. result
为我提供了正确且格式正确的JSON,但是当我尝试采用result
变量并将其设置在this.serverJSON
,它将引发错误Cannot set property 'serversJSON' of undefined
。 I want to take the value held in result and put it in serversJSON
. 我想将结果中保存的值放入
serversJSON
。 How can this be achieved and why is this
not available? 如何才能实现这一目标,为什么
this
不可用?
You are losing the context of this
within your callback function. 您正在失去的情况下
this
回调函数中。
Use a fat-arrow function (which preserves this
) instead. 请改用fat-arrow函数(保留
this
)。
xml2js.parseString(getString, (err, result) => {
this.serverJSON = result;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.