Facing issues on accessing json() in angular, HttpClient. Looking for alternatives - json

I would like to get all the posts from 'https://jsonplaceholder.typicode.com/posts'.
However the update of Http to HttpClient, not allowing to access "json()" (at response.json()).
Please guide for a solution.
Regards.
export class PostsComponent {
posts: any[];
constroctur(http: HttpClient) {
http
.get('https://jsonplaceholder.typicode.com/posts')
.subscribe((response) => {
this.posts = response.json();
});
}
}

The best way is the pass the data type to the response argument "response : any[]".
export class PostsComponent {
posts: any[];
constroctur(http: HttpClient) {
http
.get('https://jsonplaceholder.typicode.com/posts')
.subscribe((response : any[]) => {
this.posts = response;
});
}
}
You must set the content type along with the request. It should look like below.
const headers = { 'Content-Type': 'application/json'};
export class PostsComponent {
posts: any[];
constroctur(http: HttpClient) {
http
.get('https://jsonplaceholder.typicode.com/posts',{headers})
.subscribe((response : any[]) => {
this.posts = response;
});
}
}

http
.get('https://jsonplaceholder.typicode.com/posts')
.subscribe((response) => {
this.posts = response;
});
All you need to do, and arguably the best choice is setting the posts to the response. It's already a JavaScript object.
If, for whatever reason you require a JSON string, then you can look into JSON.Stringify:
this.posts = JSON.stringify(response)

Related

Angular HTTP GET

I have a server running on "localhost:3000". It displays data as JSON at e.g. "localhost:300/locations".
My "data.service.ts" includes this code:
path: string = 'http://localhost:3000'
constructor(private http: HttpClient) { }
// Locations
getAllLocations(): Observable<Location[]> {
let location = null;
this.http.get(this.path + '/locations')
.map((res => location = res))
.catch((error: any) => Observable.throw(console.log(error)));
return location;
}
In my result.component.ts I'm running this code:
constuctor(private dataservice: DataService) { }
ngOnInit() {
console.info(this.dataservice.getAllLocations());
}
I'm expecting to get as output all Locations as JSON, instead of this the output is "null".
Does anyone have a suggestion on how to make this work properly?
UPDATE:
Also tried this for the HTTP call:
getAllLocations(): Observable<Location[]> {
this.http.get<Location[]>(this.path + '/locations')
.pipe(
tap(items => console.info('fetched items'))
);
}
The output for this code is unfortunately: "Object { _isScalar: false, source: {...}, operator: {...} }"
Did you know that HttpClient#get returns an Observable? You can just return the get method in your method.
Secondly, you can set an interface to the method so that it'll return the JSON as typed.
Lastly, you can use template literals in your API URL.
/**
* Retrieves a list of locations.
* (TODO: Add better documentation here)
*/
getAllLocations(): Observable<Location[]> {
return this.http.get<Location[]>(`${this.path}/locations`);
}
You can then handle this in the actual component that calls this method:
constuctor(private dataservice: DataService) { }
ngOnInit() {
this.dataservice.getAllLocations().subscribe(result => {
console.log(result);
});
}
You have to return Observable from the service:
path: string = 'http://localhost:3000'
constructor(private http: HttpClient) { }
// Locations
getAllLocations(): Observable<Locations[]> {
return this.http.get(this.path + '/locations').pipe(
map((res => location = res)),
catch((error: any) => Observable.throw(console.log(error))));
}
And subscribe to it in the component.
constructor(private dataservice: DataService) { }
ngOnInit() {
this.dataservice.getAllLocations().subscribe(result => {
console.log(result);
})
}

Property 'locations' does not exist on type 'Object'

import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import 'rxjs/add/operator/map';
#Injectable()
export class LocationsProvider {
data: any;
constructor(public http: HttpClient) {
}
load() {
if (this.data) {
return Promise.resolve(this.data);
}
return new Promise(resolve => {
this.http.get('assets/data/locations.json').subscribe(data => {
this.data = this.applyHaversine(data.locations);
this.data.sort((locationA, locationB) => {
return locationA.distance - locationB.distance;
});
resolve(this.data);
});
});
}
enter image description here
i am pretty new here, and pretty new to ionic, i'll probably requires detailed solution, i cant seems to make ionic read a json file
You are getting a compile time error in data.locations specifically locations is not defined on the data property.
Fix
Tell TypeScript that it is e.g. use an assertion:
this.data = this.applyHaversine((data as any).locations);
If you know the type of your response, you can add a generic to http.get<T>() to type data.
interface SomeInterface {
locations: Location[]
}
this.http.get('assets/data/locations.json')<SomeInterface>.subscribe(data => {
this.data = this.applyHaversine(data.locations);
...
});
or if you don't want to create an interface for it (not recommended)
this.http.get('assets/data/locations.json')<SomeInterface>.subscribe((data: any) => {
this.data = this.applyHaversine(data.locations);
...
});

How can I save http get response object in angular 6

I'm new to angular and i'm trying to figure out how can I save in a local variable the response of http.get(url)
Here is my code :
export class AppComponent {
private url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&api_key=MY_KEY&format=json&artist=The+Weeknd' ;
public data;
constructor(private http: HttpClient) {
this.http.get(this.url).subscribe(response => this.data = response);
console.log(this.data); // -> The result is undefined...
}
}
At first, I tried this.http.get(this.url).subscribe(response => console.log(response)); and that was working has expected, however an assignation doesn't work.
Thanks a lot !
You're code is exactly correct. The reason the console.log is not showing the response value is because it is running BEFORE the response is processed. Once the HTTP request has been started, JavaScript continues executing the current function.
If you want to log the response, you need to do so inside the response handler
export class AppComponent {
private url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&api_key=MY_KEY&format=json&artist=The+Weeknd' ;
public data;
constructor(private http: HttpClient) {
this.http.get(this.url).subscribe(response => {
this.data = response;
console.log(this.data);
});
}
}
You are doing async HTTP call. so you need to add console.log inside subscribe.
export class AppComponent {
private url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&api_key=MY_KEY&format=json&artist=The+Weeknd' ;
public data;
constructor(private http: HttpClient) {
this.http.get(this.url).subscribe(response => {
this.data = response;
console.log(this.data);
});
}

Get contents of json file not working

I want to get a json object from a json file using angular 2 http.get. What I end up getting from the file is this:
t_isScalar: falseoperator: tsource: t__proto__: Object
Here is my code
#Injectable()
export class ValidateJSONSchemaService {
constructor(private http: Http) { }
getSchema(fileName): any {
return(this.http.get(fileName)
.map(this.extractData)
);
}
private extractData(res: Response) {
let body = res.json();
return body.data || {};
}
}
How do I fix getSchema to make it return the json object rather than this: t_isScalar: falseoperator: tsource: t__proto__: Object. Note that when I change the file name it returns the same thing. I would have expected an informational error (I did do error handling but the code never errors out).
You need to subscribe to observable:
#Injectable()
export class ValidateJSONSchemaService {
constructor(private http: Http) { }
getSchema(fileName): any {
return(this.http.get(fileName)
.map(this.extractData).subscribe(data => console.log(data));
);
}
private extractData(res: Response) {
let body = res.json();
return body.data || {};
}
}
In addition to Maciej s answer you can use the | async pipe that does the subscribing for you.
<div>{{getSchmea('fileName') | async}}</div>

Accessing data within a view passed from model - Aurelia

Yes another Aurelia question, apologies!
So I'm trying to access data within my view passed from a model, whilst I can see the data within the response, I cannot seem to get it to display on the view. Any help greatly appreciated.
I've tried a few things but I guess being new to Aurelia,ES6 and promises, it's throwing me out a little or I've been staring at to long.
//EDIT Data Access Component
import {inject} from "aurelia-framework";
import {HttpClient} from "aurelia-http-client";
let baseUrl = "/FormDesigner";
#inject(HttpClient)
export class FormData{
constructor(httpClient)
{
this.http = httpClient;
}
GetFormById(formId)
{
return this.http.get(`${baseUrl}/GetFormById/${formId}`)
.then(f => f.content);
};
}
Model:
activate(params)
{
return this.form.GetFormById(params.formId)
.then(f => this.form = f);
}
The View:
<p class="navbar-text navbar-left">
${form.name}
</p>
The Response:
{"Id":"x","OrganisationId":"x","OrganisationDepartmentId":null,"ScheduleId":null,"DefinitionTypeId":"x","ReferenceNumber":11171,"Name":"New Form Test External Access","Description":"","IsTemplate":true,"IsActive":true,"IsSingleFormTemplate":false,"MinimumInstances":null,"MaximumInstances":null,"IsAdhocCreationEnabled":false,"HasCalculation":false,"Calculation":null,"Recalculate":true,"IsHidden":false}
So again I don't see the data appearing on the view and I feel I'm missing something rather simple.
//EDITS
So after a little digging I made a little change to my API returning a JSON array rather than a JSON object and also switched Aurelia to use Fetch... So now I can access the data in my data component but not my model - rather frustrating!
import {inject} from "aurelia-framework";
//import {HttpClient} from "aurelia-http-client";
//import 'fetch';
import {HttpClient} from 'aurelia-fetch-client';
let baseUrl = "/FormDesigner";
#inject(HttpClient)
export class FormData{
constructor(httpClient)
{
httpClient.configure(config => {
config
.withBaseUrl('/FormDesigner')
.withDefaults({
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'X-Requested-With': 'Fetch'
}
})
.withInterceptor({
request(request) {
console.log(`Requesting ${request.method} ${request.url}`);
return request;
},
response(response) {
console.log(`Received ${response.status} ${response.url}`);
return response;
}
});
});
this.http = httpClient;
}
GetFormById(formId)
{
return this.http.fetch(`/GetFormById/${formId}`)
.then(response => response.json())
.then(data => {
//Log here, to check incoming data
console.log("From component: " + data.Name);
//This WORKS
});
};
}
Again I've created an abstraction where as my model does not need to know about calls to the server.
import {inject} from "aurelia-framework";
import {FormData} from "form/formData";
#inject(FormData)
export class Form
{
constructor(formData)
{
this.form = formData;
}
activate(params)
{
if(params.formId != null)
{
return this.form.GetFormById(params.formId)
.then(data =>
{
this.form = data
console.log(this.form.Name);
//This does not work!!
});
}
else
{
//Show message that param does not exist or redirect to no form page
console.log("No Id");
}
}
}
Any help greatly appreciated,
Most likely you need to deserialize the JSON response into a Javascript object using JSON.parse.
GetFormById(formId)
{
return this.http.get(`${baseUrl}/GetFormById/${formId}`)
.then(response => JSON.parse(response.content));
};