gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:00:26 24 4
gpt4 key购买 nike

我有一些代码正在读取 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com