How to get a response body using Observables - json

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

Related

Angular 2 api data

I want to get data from Riot API and display it in html view.
However, i can not "hold" this data in my variable. Console log show empty array.
I can see json data only in function scope.
I guess, i didn`t use observable function corretly, am i wrong?
Here is my component.
import { Component, OnInit } from '#angular/core';
import { FRIEND } from '../../services/_friends/mock-friends';
import { APIKEY } from '../../services/_lolapi/apikey';
import { Http, Response } from '#angular/http';
import { KeysPipe } from '../../pipes/key';
import { JsonPipe } from '#angular/common';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
#Component({
selector: 'app-friends',
templateUrl: './friends.component.html',
styleUrls: ['./friends.component.css']
})
export class FriendsComponent implements OnInit {
friends = FRIEND;
apikey = APIKEY;
nick: string[];
query: string;
private apiUrl =
'https://eun1.api.riotgames.com/lol/summoner/v3/summoners/by-name/';
data: Array<string> = [];
constructor(private http: Http) {
}
getFriendData(query) {
return this.http.get(query)
.map((res: Response) => res.json());
}
getContacts() {
this.getFriendData(this.query).subscribe(data => {
this.data = data;
console.log(this.data);
});
}
ngOnInit() {
for (let i of this.friends) {
this.query = `${this.apiUrl}${i.nick}${this.apikey}`;
this.getFriendData(this.query);
this.getContacts();
console.log(i.nick);
}
}
}
You don't need this.getFriendData(this.query) in ngOnInit as in the next line you call getContacts that wraps getFriendData.
Now, your API returns SummonerDTO - a complex object and you are trying to store it as an Array? That doesn't seem right.
Additionally, it think you want to store every result in an array, right?
In that case you should rather use:
this.data.push(data);

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

Load JSON data into Angular 2 Component

I am trying to load JSON hada into an Angular 2 Component, and I think I have found the way.
datoer.service.ts:
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Observable } from 'rxjs/Observable';
#Injectable()
export class DatoService {
dato: Array<any>;
constructor(private http: Http) {}
getDato() {
return this.http.request('./datoer.json')
.map(res => res.json());
}
}
kalender.component.ts:
import { Component } from '#angular/core';
import { ValgteSkolerService } from '../valgteSkoler.service';
import { DatoService } from './datoer.service';
#Component({
selector: 'kalender',
providers: [DatoService],
templateUrl: 'app/kalendervisning/html/kalender.html'
})
export class KalenderComponent {
private valgteSkoleRuter: Array<any>= [];
//private datoer: Array<any> = [];
constructor(private valgteSkolerService: ValgteSkolerService, private DatoService: DatoService) {
this.datoer = this.DatoService.getDato();
}
ngOnInit() {
this.valgteSkolerService.hentLagretData();
this.valgteSkoleRuter = this.valgteSkolerService.delteValgteSkoleRuter;
}
My template is like:
<p *ngFor="let dato of datoer"> {{dato}} </p>
My problem is the this.datoer above in the component. It says it does not exist on type KalenderComponent.
I have tried declaring it like this in the component:
private datoer: Array<any> = [];
But then it says that "Type 'Observable' is not assignable to type 'any[]'. Property 'length' is missing in type 'Observable'.
Any ideas how to solve this?
The http service, according to Angular2 Http class docs, returns an observable not an array with results, that's because it's made asynchronously. Therefore you must subscribe to the observable so you can feed your array when it gets notified (this happens when http request is complete).
For example:
public datoer: any[] = [];
constructor(
private valgteSkolerService: ValgteSkolerService,
private DatoService: DatoService) {
this.DatoService
.getDato()
.subscribe(datoer => { this.datoer = datoer; });
}

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.