javascript - Angular/Typescript 无法设置未定义的属性 'data'

标签 javascript angular typescript

我有一些代码正在读取 xml 然后解析数据。

所以这是代码:

data = [];

  ngOnInit() {
  this.myService.getData().subscribe(XMLResult => {
    const parseString = require('xml2js').parseString;
    parseString(XMLResult, function (err, result) {
       console.dir(result.listResponse.instance); // Returns Array
       this.data = result.listResponse.instance; // Here's the line giving me the error
    });

 });
}

Console.log 返回的数据如下:

Array(10)
  0:
   $: {id: "23" name: "name 1"}
  1:
   $: {id: "45" name: "name 2"}

等等

如何解决这个问题?

最佳答案

在您当前的方法中,this 不再引用您的组件。

修改您的回调以使用箭头函数,这样您就不会失去范围:

parseString(XMLResult, (err, result) => {
  console.dir(result.listResponse.instance);
  this.data = result.listResponse.instance;
})

Docs

Until arrow functions, every new function defined its own this value (a new object in the case of a constructor, undefined in strict mode function calls, the base object if the function is called as an "object method", etc.). This proved to be less than ideal with an object-oriented style of programming.

关于javascript - Angular/Typescript 无法设置未定义的属性 'data',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50060007/

相关文章:

javascript - ASP :Net Required field turn control back color red for validation groups

Javascript touch 事件打破了 iPad 上的垂直滚动

Angular 10 : Cannot find name when trying to import module

javascript - 检测重叠元素中的悬停,同时允许所有指针操作

angular - 如何检查 react 形式的任何控件是否在 Angular 2 中具有值(value)

javascript - 正则表达式仅匹配错误匹配的数字

javascript - 如何在不以 channel 所有者身份登录谷歌的情况下使用 Youtube Analytics API 从授权 channel 接收数据?

angular - Angular 中的绑定(bind)回调函数

typescript - Angular2 农业网格数据源

html - 基于 Ionic 3 中的第一个 DropDownSelect 显示/隐藏第二个 DropDownSelect