jus*_*ech 2 xml json typescript xml2js angular
到目前为止,我无法使用 Angular 6 让 xml2js 代码正常工作。我有一个 service.ts 返回 xml,但是当调用 xml2js.parseString 转换为 json 时,我始终收到未定义的错误。
“core.js:1673错误TypeError:无法读取未定义的属性'parseString'”
服务.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
}
)
)
}
}
Run Code Online (Sandbox Code Playgroud)
组件.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() {
}
}
Run Code Online (Sandbox Code Playgroud)
我已将返回的 xml 运行到在线转换器,没有遇到任何问题。我不知道为什么该函数返回未定义。
还有一种方法可以验证 xml2js 中的所有文件是否已正确加载?
将课堂上的导入更改CgetterComponent为:
import xml2js from 'xml2js';
Run Code Online (Sandbox Code Playgroud)
或者:
import * as xml2js from 'xml2js';
Run Code Online (Sandbox Code Playgroud)
如果您检查在项目main的package.json. 它导出一个具有各种属性的对象,例如Builder、Parser、 和parseString,但它们都没有名称/标识符xml2js。因此,您正在使用的命名导入import { xml2js } from 'xml2js';试图重要一个不存在的对象属性(登录xml2js我共享的示例以查看导出的属性),因此undefined.
您可以采取的另一种导入方法是使用命名导入来直接导入parseString您正在使用的函数。这看起来像:
import { parseString } from 'xml2js';
Run Code Online (Sandbox Code Playgroud)
然后您只需按如下方式使用它:
parseString(data, { explicitArray: false }, (error, result) => {
if (error) {
throw new Error(error);
} else {
res = result;
console.log(result);
}
});
Run Code Online (Sandbox Code Playgroud)
以下是实际导入/使用的示例。
希望这有帮助!
| 归档时间: |
|
| 查看次数: |
8509 次 |
| 最近记录: |