angular 6 中未定义的 parseString 使用 xml2js

parseString undefined in angular 6 using xml2js

到目前为止,我无法使用 angular 6 使 xml2js 代码正常工作。我有一个 service.ts 返回 xml 但是在调用 xml2js.parseString 时转换为 json 我总是收到未定义的错误。

"core.js:1673 错误类型错误:无法读取未定义的 属性 'parseString' “

service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { map, filter, catchError, mergeMap } from 'rxjs/operators';
import { HttpHeaders } from '@angular/common/http';

export interface Zid {
  zpid: number;
}
const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/x-www-form-urlencoded',
  }),
  responseType: 'text' as 'text'
};    

@Injectable({
  providedIn: 'root'
})

export class CdataServiceService {

  constructor(private _http: HttpClient) { }
  zipID = 'http://APiXml';
  getZipID() {
    return this._http.get(this.zipID, httpOptions)
    .pipe
      (map
        (res => 
          {
            return res
          }
        )
      )
  }
}

component.ts

import { Component, OnInit } from '@angular/core';
import { CdataServiceService, Zid } from '../cdata-service.service';
import { xml2js } from 'xml2js';
import { Observable, of } from 'rxjs';

@Component({
  selector: 'app-cgetter',
  templateUrl: './cgetter.component.html',
  styleUrls: ['./cgetter.component.css']
})
export class CgetterComponent implements OnInit {

  data = [];

  constructor(private cds: CdataServiceService) { }

  onKeyCompGet(event:any){
    console.log(event.target.value);
  }
  _zid :Zid

  getTheComps(){
    this.cds.getZipID()//cdataServiceService.getZipId()
    .subscribe(
      res => {
        this.convertToJson(res);
     })
  }


  public convertToJson(data: string): Object {

    let res;
    console.log(data);

    xml2js.parseString(data, { explicitArray: false }, (error, result) => {

      if (error) {
        throw new Error(error);
      } else {
        res = result;
        console.log(result);
      }

    });

    return res;

  }

  ngOnInit() {
  }

}

我已经 运行 将 xml 返回到在线转换器并且 运行 没有遇到任何问题。我不知道为什么函数 returns undefined.

还有没有办法验证 xml2js 中的所有文件是否正确加载?

将 class CgetterComponent 中的导入更改为:

import xml2js from 'xml2js';

或:

import * as xml2js from 'xml2js';

如果你检查你正在使用的 import { xml2js } from 'xml2js';xml2js file which is referenced as the main file in the project's package.json. It exports an object with various properties such as Builder, Parser, and parseString, none of them have the name/identifier xml2js. So the named import 试图重要一个不存在的对象 属性 (在我分享的示例中记录 xml2js查看导出的属性),因此 undefined.

您可以采用的另一种导入方法是使用命名导入直接导入您正在使用的 parseString 函数。这看起来像:

import { parseString } from 'xml2js';

然后您只需按如下方式使用它:

parseString(data, { explicitArray: false }, (error, result) => {
  if (error) {
    throw new Error(error);
  } else {
    res = result;
    console.log(result);
  }
});

这是 import/usage 的 example 的实际效果。

希望对您有所帮助!