【发布时间】:2019-11-18 22:24:49
【问题描述】:
编辑:这不适用于 xml2js npm 包,因为我想做相反的事情,将 json 转换为 xml,而不是相反。
我的 API 使用 JSON 数据格式,但我还必须将我更新的对象保存在 XML 格式的文本文件中,因为我们与之通信的其他应用程序只接受 XML 格式。
我有我的服务
shipment.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import * as x2js from 'xml2js';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ShipmentService {
baseUrl = "http://localhost:5000/api/shipments/"
constructor(
private http: HttpClient
) {}
getShipments() {
return this.http.get(this.baseUrl);
}
getShipment(id) {
return this.http.get(this.baseUrl + id);
}
updateShipment(id: number, shipment) {
return this.http.put(this.baseUrl + id, shipment);
}
}
还有tracker.component.ts
import { Component, OnInit } from '@angular/core';
import { ShipmentService } from 'src/app/services/shipment.service';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ShipmentModalComponent } from '../shipment-modal/shipment-modal.component';
import { Router } from '@angular/router';
import { NgxSpinnerService} from 'ngx-spinner';
var convert = require('xml-js');
@Component({
selector: 'app-tracker',
templateUrl: './tracker.component.html',
styleUrls: ['./tracker.component.css']
})
export class TrackerComponent implements OnInit {
shipments:any = [];
shipment:any = {};
modal_on:boolean = false;
modalcontent:any;
closeResult = '';
reference: string;
constructor(
private shipmentService: ShipmentService,
private modalService: NgbModal,
private spinner: NgxSpinnerService,
private router: Router
) {}
ngOnInit() {
this.getShipments();
}
convertToXML(json) {
var options = {compact: true};
var result = convert.json2xml(json, options);
console.log(result);
}
getShipments() {
this.spinner.show(undefined,{
type: "square-spin",
size: "medium",
bdColor: 'rgba(0,0,0,.5)',
color: "rgb(5, 5, 80)",
fullScreen: false
});
this.shipmentService.getShipments().subscribe(response => {
this.shipments = response;
this.spinner.hide();
this.convertToXML(response);
console.log(response);
}, error => {
console.log(error);
});
}
}
所以我尝试使用 x2js 和其他 xml2json 库,但我没有成功将 JSON 对象转换为 XML 对象或字符串。
【问题讨论】:
-
请给minimal reproducible example; “没有成功”究竟是什么意思?
-
您在代码的哪个位置进行转换?
-
我添加了请求对象的依赖项和方法,我需要将json响应转换为xml对象。
标签: javascript json angular xml angular7