0

I was parsing some data via API my code for the parsing is given below,

  parseXML(data) {
    return new Promise((resolve) => {
      var k: string | number,
        arr = [],
        parser = new xml2js.Parser({
          trim: true,
          explicitArray: true,
        });
      parser.parseString(data, function (err, result) {
        var obj = result.ApiResponse;
        for (k in obj.CommandResponse) {
          var item = obj.CommandResponse[k];
          arr.push({
            info: item.DomainCheckResult[0],
          });
        }
        resolve(arr);
      });
    });
  }

This is my parser code but still i'm getting console error with
core.js:4197 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'Parser' of undefined TypeError: Cannot read property 'Parser' of undefined

So my question was what's wrong with the code? as I was returning a promise what extra could I do? I'm returning a new promise and after that I have called the parser, so how could I get error? Can anyone help me?

MD Nasirul Islam
  • 501
  • 5
  • 17
  • Well, it says that the xml2js object is not set. Maybe you have to initialize it/import it. The new keyword is in that context not enough. – derstauner Oct 03 '20 at 11:06
  • I have declared the object but still, it's not getting the data. On top `import { xml2js } from 'xml2js';` – MD Nasirul Islam Oct 03 '20 at 11:22
  • Check this post: https://stackoverflow.com/questions/53052221/parsestring-undefined-in-angular-6-using-xml2js – derstauner Oct 04 '20 at 05:34
  • @derstauner Thank you for your comment. Your link is very helpful. I did solve the problem. well, there was a typo error on the code mainly it would be a coma thats all. – MD Nasirul Islam Oct 04 '20 at 10:06

1 Answers1

0

Well, there should be a ',' instead of the ';'. After tweaking for a long time I was finally able to solve the problem.

  parseXML(data) {
    return new Promise((resolve) => {
      var k: string | number,
        arr = [],
        parser = new xml2js.Parser({
          trim: true,
          explicitArray: true,
        });
      // var parser = new xml2js.Parser({ explicitArray: false });
      parser.parseString(data, function (err, result) {
        var obj = result.ApiResponse;
        for (k in obj.CommandResponse) {
          var item = obj.CommandResponse[k];
          arr.push({
            Name: item.DomainCheckResult[0]['$']['Domain'],
            Available: item.DomainCheckResult[0]['$']['Available'],
            PremiumRegistrationPrice:
              item.DomainCheckResult[0]['$']['PremiumRegistrationPrice'],
          });
        }     console.log(JSON.stringify(item.DomainCheckResult));
      });
    });
  }

BTW thank you everyone who tried to help. Ohh and another thing on the top I also did an error on importing the xml2js I also had to change that.

import xml2js from 'xml2js';

MD Nasirul Islam
  • 501
  • 5
  • 17