简体   繁体   English

parseString方法中的成员未定义

[英]Member undefined inside parseString method

I have XML file I need to convert to Json so I can use in my application. 我有需要转换为Json的XML文件,因此可以在我的应用程序中使用。 In my service I return the XML file: 在我的服务中,我返回XML文件:

constructor(private http: HttpClient) { }

loadXml() {
  return this.http.get('../../assets/1bbc5495-3872-4058-886e-aeee2a1cd52c.xml', { responseType: 'text' });
}

In my component I try to get the data inside the XML file available: 在我的组件中,我尝试获取XML文件中的数据:

parseString = require('xml2js').parseString;
data = [];

constructor(
  private _sharedService: SharedService
) {}

ngOnInit() {
  this.convertXmlToJson();
}

convertXmlToJson() {
  let data;
  this._sharedService.loadXml()
    .subscribe(
      res => {
        this.parseString(res, function (err, result) {
          this.data = result.rss.channel[0];
        });
      }
    )
}

This results in the error: 这导致错误:

Cannot set property 'data' of undefined 无法设置未定义的属性“数据”

Why can't I use this.data ? 为什么我不能使用this.data

//EDIT. //编辑。

This might not be the best method but it works: 这可能不是最好的方法,但它可以工作:

convertXmlToJson() {
  let data;
  this._sharedService.loadXml()
    .subscribe(
      res => {
        this.setData(res)
      }
    )
}

setData(res) {
  let data;
  this.parseString(res, function (err, result) {
    data = result.rss.channel[0]
  })
  this.data = data;
}

I now pass the data from the method in the service to a function that stores it in a function variable and I set that variable on the class member. 现在,我将数据从服务中的方法传递给将其存储在函数变量中的函数,然后在类成员上设置该变量。

You are losing the context( this ) inside the subscription's response. 您正在丢失订阅响应中的上下文( this )。

convertXmlToJson() {
  let data;
  this._sharedService.loadXml()
    .subscribe(
      res => {
        this.parseString(res, (err, result) => this.data = result.rss.channel[0]).bind(this);
      }
    )
}

That's why we need to pass with with bind() or call() . 这就是为什么我们需要通过bind()call()进行传递。

bind() mostly for functions that are being called as callbacks and call() for functions out of scope (don't have the this context) but are using the this keyword. bind()主要用于被称为回调的函数,而call()用于超出范围的函数(不具有this上下文),但是使用this关键字。

Example: 例:

function foo() {
  this.myBool = !this.myBool;
}

class MyClass {
  myBool = false;

  foo.call(this); // will read this.myBool because we are passing the context

  someSubscription.subscribe(
    resp => foo().bind(this) // being a callback function you need to pass the this context with a bind()
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM