'this' 在 Angular 中未定义,XML2JS

'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
            });
        });
      }
}

在此代码中,指示的行似乎无法访问 this。控制台日志显示 undefinedresult 给了我一个正确且格式化的 JSON,但是当我尝试获取 result 变量并将其设置在 this.serverJSON 中时,它会抛出错误 Cannot set property 'serversJSON' of undefined . 我想获取结果中的值并将其放入 serversJSON。 如何实现,为什么 this 不可用?

您正在丢失回调函数中 this 的上下文。

改为使用粗箭头函数(保留 this)。

xml2js.parseString(getString, (err, result) => {
  this.serverJSON = result;
});