簡體   English   中英

Angular / Typescript無法設置未定義的屬性“數據”

[英]Angular / Typescript Cannot set property 'data' of undefined

我有一些代碼正在讀取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;
})

文件

在使用箭頭函數之前,每個新函數都定義了自己的該值(對於構造函數而言,是新對象,在嚴格模式下的函數調用中未定義;如果該函數稱為“對象方法”,則為基礎對象,等等)。 事實證明,使用面向對象的編程風格並不理想。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM