编辑:添加了其他导入和依赖项。
我有使用JSON数据格式的API,但是我还必须将更新的对象以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对象或字符串没有成功。
安装npm i js2xmlparser