Converting XML API response to JSON in Angular - json

I am receiving data from an API that uses XML instead of JSON. So far I have the following service for connecting to the API:
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class MyService {
private searchURL: string = "http://api.testsite.xml";
constructor(private _http: Http) { }
getData(){
return this._http.get(this.searchURL).map(res => res)
}
}
I subscribe to it in my component like so:
ngOnInit() {
this._service.getData().subscribe(item=> console.log((<any>item)._body));
}
This returns a Response object inside which there's a _body property where the whole XML is stored as a string. How do I go about extracting this XML and convert it to JSON? Thanks.

You can use -
xml2json.js library. Found this at - Here
var x2js = new X2JS();
var jsonString = x2js.xml_str2json(yourXml);

Related

How to get a response body using Observables

I'm using the ng-book as a reference and one of those examples uses observable to get json data but now I want to retrieve data for my own project using a different api which is this http://mindicador.cl/api
but I got an error which is "Return expression type is not assignable to type Observables". How can I solve this? or How can I get json data with observables?
import {
Injectable,
Inject
} from '#angular/core';
import {Observable} from 'rxjs';
import {HttpClient} from '#angular/common/http';
import {Indicadores} from '../indicadores/indicadores.model';
export const MINDICADOR_API = 'http://mindicador.cl/api';
#Injectable()
export class MindicadorService {
constructor(private http: HttpClient, #Inject(MINDICADOR_API) private apiUrl: string) {
}
search(): Observable<Indicadores> {
const queryUrl = this.apiUrl;
return this.http.get(queryUrl)
.subscribe((res) => {
return new Indicadores()
});
}
}
You were try to return from subscribe, which tends to return subscription object.
It seems like you want to return a data Observable<Indicadores> so have <Indicadores> is enough after http.get
search(): Observable<Indicadores> {
const queryUrl = this.apiUrl;
return this.http.get<Indicadores>(queryUrl);
}
You need to return the observable from the service as below:
search(): Observable<Indicadores> {
const queryUrl = this.apiUrl;
return this.http.get(queryUrl)
);
}
And in your controller, use the .subscribe to get the data

Angular 5, rxjs map to json, 'json' does not exist on the the type 'object

Trying to follow an online video, then this appears, I am new to angular, other solutions are not helping me out.
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import 'rxjs/add/operator/map';
/*
Generated class for the WeatherProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
#Injectable()
export class WeatherProvider {
apikey='7d2dc7a226a78c14';
url;
constructor(public http: HttpClient) {
console.log('Hello WeatherProvider Provider');
this.url='http://api.wunderground.com/api/'+this.apikey+'/conditions/q'
}
getWeather(city,state){
return this.http.get(this.url+'/'+state+'/'+city+'.json')
.map(res => res.json() );
}
}
If you're using the new HttpClient you don't need to parse JSON because it's decoded automatically for you:
https://angular.io/guide/http#type-checking-the-response
The HttpClient.get() method parsed the JSON server response into the anonymous Object type. It doesn't know what the shape of that object is.
Also https://angular.io/guide/http#requesting-non-json-data.
With angular 5 and httpClient, you don't need to use the map part anymore.
Read more here: https://angular.io/guide/http#type-checking-the-response
getWeather(city,state){
return this.http.get(this.url+'/'+state+'/'+city+'.json');
}
If you want to get data in specific format, You can tell HttpClient the type of the response to make consuming the output easier and more obvious.
export interface Config {
heroesUrl: string;
textfile: string;
}
And then :
getConfig() {
// now returns an Observable of Config
return this.http.get<Config>(this.configUrl);
}

How to convert an object to JSON in Angular

Found some answers for angularjs like: How to use angular.toJson on a angular controller or scope but not Angular 2 and following.
I'm new to Angular, worked through the tutorial, and now trying to build my first live app. I have a credentials object that has fields username and password. I want to externalize this to JSON to send to my web service. I found this: https://angular.io/api/common/JsonPipe which seems to do what I want, but the example is in HTML and I want to do it in my service, so here's my service:
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { JsonPipe } from '#angular/common';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
#Injectable()
export class LoginService {
authToken = ""
loginUrl = "localhost:8093/login"
constructor(private http: HttpClient) { }
login(credentials): Observable<String> {
var url = this.loginUrl
+ '?payload='
+ (credentials | json)
return of(url);
}
}
But I get an error on the line + (credentials | json) saying json is not found, maybe I meant JSON?
Did I?
Just use
JSON.stringify(credentials)
like in plain JavaScript.
The | json pipe is only for view binding like
{{credentials | json}}
but not for TypeScript code.

Ionic 2 - Turning HTTP GET JSON Response into an array of items

I am working on an app and am having difficulty using an API call to Eventbrite in a provider, parsing the JSON it returns, and inserting the data I want into an array.
Here is my provider (event-provider.ts):
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import {NativeStorage} from "ionic-native";
import 'rxjs/add/operator/map';
/*
Generated class for the EventProvider provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
#Injectable()
export class EventProvider {
constructor(public http: Http) {
console.log("Event Provider")
}
public getJsonData(){
return this.http.get('https://www.eventbriteapi.com/v3/events/search/?location.address=Atlanta&expand=organizer,venue&token=VMGQGYQUIO3IKNS75BD4').map(res => res.json().events);
}
//console.log('Hello EventProvider Provider');
}
And here is the event page in which I eventually will list the data (events.ts):
import { Component } from '#angular/core';
import {EventProvider} from '../../providers/event-provider';
import { NavController } from 'ionic-angular';
#Component({
selector: 'event-list',
templateUrl: 'events.html',
providers: [EventProvider]
})
export class EventsPage {
events = []
constructor(public navCtrl: NavController, private eventProvider: EventProvider) {
this.events = eventProvider.getJsonData();
}
}
For the above .ts file I am getting an error at this.events = eventProvider.getJsonData();. The error says: Type 'Observable' is not assignable to type 'any[]'. Property 'find' is missing in type 'Observable'. I do not really understand this error.
This is what the JSON response looks like: EventBrite
Basically, I want to add each event as an item to an array. The JSON response contains about 500 events.
I've just stuck at the moment an not sure if on on the right track. It is hard to debug my code because it is being tested in an iOS emulator and thus the console.log() doesn't work. Any tips on how to reach my goal of creating an array of events from the JSON response?
You need to subscribe to observables in order to make a request.
this.events = eventProvider.getJsonData();
should be something like:
eventProvider.getJsonData().subscribe((res)=>{
this.events = res.events;
});
And Also you need to return that json and assuming you always have event properties in the response:
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import {NativeStorage} from "ionic-native";
import 'rxjs/add/operator/map';
/*
Generated class for the EventProvider provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
#Injectable()
export class EventProvider {
constructor(public http: Http) {
console.log("Event Provider")
}
public getJsonData(){
return this.http.get('yourUrl')
.map(res => {
let body = res.json();
return body.events || { };
});
}
}

SyntaxError: Unexpected token < in JSON at position 3 in ionic 2

I'm having an error in Ionic 2 "SyntaxError: Unexpected token < in JSON at position 3". My json format is correctly structured using spring boot.
Below is my spring boot code.
Appreciate your help.
#RequestMapping(value="/myview", method=RequestMethod.GET, produces = "application/json")
#ResponseBody
List<Client> myView( #ModelAttribute("client") Client client){
List<Client> data=(List<Client>) clientService.getAll();
return data;
}
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class PeopleService {
people: any;
constructor(public http: Http) {}
load(){
if (this.people) {
return Promise.resolve(this.people);
}
return new Promise(resolve => {
this.http.get('http://localhost:8080/myview')
.map((res)=>res.json()).subscribe((data)=>{
console.log(data);
this.people=data;
resolve(this.people);
}, err=>{console.log(err)});
});
}// end load function
}
JSON from /myview
[{"id":1,"username":"donald#yahoo.com","policy":"V121293031","name":"Donald","mobile":"0504735260","email":"dcgatan#gmail.com","address":"Dafza Dubai","amount":800.98,"datetimestamp":1472861297000},{"id":3,"username":"dcgatan78#gmail.com","policyno":"V38998933","fname":"Donald","mobile":"0501234567","email":"dcgatan#gmail.com","address":"MetDubai","amount":334.34,"datetimestamp":1472862939000},{"id":4,"username":"dcgatan#yahoo.com","policyno":"V34342323","fname":"Snoopy","mobile":"0501234567","email":"dcgatan#yahoo.com","address":"Metlife Dafza Dubai","amount":883.43,"datetimestamp":1472916463000}]
My http://localhost:8080/myview is not working because when I tried the below code with Array value it works. How to call the http instead of putting static values in the Array?
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class PeopleService {
people: Array<any> = [{"id":1,"username":"donald#yahoo.com","policyno":"V121293031","fname":"Donald","mobile":"0504735250","email":"dcgatan#gmail.com","address":"Dafza Dubai","amount":800.98,"datetimestamp":1472861297000},{"id":3,"username":"dcgatan78#gmail.com","policyno":"V38998933","fname":"Donald","mobile":"0501234567","email":"dcgatan#gmail.com","address":"MetLife Dubai","amount":334.34,"datetimestamp":1472862939000}];
constructor(private http: Http) {}
load(){
if (this.people) {
return Promise.resolve(this.people);
}
return new Promise(resolve => {
this.http.get('http://localhost:8080/myview')
.map((res)=>res.json())
.subscribe((data)=>{
this.setPeople(data);
resolve(this.people);
});
});
}// end load function
setPeople(data) {
if (data) {
for (let id of Object.keys(data)) {
let item = data[id];
item.id = id;
this.people.push(item);
}
}
}
}
Your call to /myview would be returning incorrect json. It must be having HTML elements. Performing res.json() extracts data from _body of the response, if it's valid. But in your case it is throwing an error.