到目前为止,我无法使用 Angular 6 让 xml2js 代码工作。我有一个返回 xml 的 service.ts 但是当调用 xml2js.parseString 转换为 json 时,我一直收到一个未定义的错误。
“core.js:1673 错误类型错误:无法读取未定义的属性‘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
}
)
)
}
}
组件.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 运行到在线转换器并且没有遇到任何问题。我不知道为什么函数返回未定义。
还有一种方法可以验证 xml2js 中的所有文件是否正确加载?