How to convert an object to JSON in Angular - json

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.

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 map the angular 5 service response to JSON object

In the earlier angular version, in our service, we could simply map the response to a JSON object as follow :
import { Injectable } from '#angular/core';
import 'rxjs/add/operator/map';
import { HttpClient } from '#angular/common/http';
#Injectable()
export class MakeService {
constructor(private http:HttpClient) { }
getMakes(){
return this.http.get('/api/myAPI')
.map(res=>res.json());
}
}
However, in angular 5 we don't have HTTP anymore and we have to use HttpClient instead, what should be added to the code above to work in angular5.
my component looks like :
makes : any[];
constructor(private makeservice: MakeService) { }
ngOnInit() {
this.makeservice.getMakes().subscribe(makes=>{
this.makes=makes;
console.log("MAKES",this.makes);
});
}
simply by removing the ":any[]" data type from make it will work, but I need to pass the JSON object to component from service.
Try the following,
getMakes(){
return this.http.get('/api/myAPI')
}
and in component,
constructor(public data:DMakeService ){
this.data.getMakes().subscribe(data=>{
console.log(data);
})
}
You don't need to map to JSON anymore, so this is sufficient:
getMakes(){
return this.http.get('/api/myAPI');
}
This returns an Observable, however, not a Promise, so you'd have to subscribe the return value to get the result. If you want to keep working with promises, you can do this:
getMakes(){
return this.http.get('/api/myAPI').toPromise();
}
According here. You should always subscribe to any request made by httpclient
Always subscribe!
An HttpClient method does not begin its HTTP request until you call
subscribe() on the observable returned by that method. This is true
for all HttpClient methods.
const req = http.get<Heroes>('/api/heroes');
// 0 requests made - .subscribe() not called.
req.subscribe();
// 1 request made.
req.subscribe();
// 2 requests made.

Converting XML API response to JSON in Angular

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);

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 || { };
});
}
}