how to fetch data from json in angular 4 - json

Hi everyone plz help me I have Json string which is I am getting from Node api .I want only single value from that string.
I have service.ts from which I am calling api and subscribe the data on my component file .
Json string is [{"_id":5,"name":"ram,shyam,kamal,kishore"}]
I want only name value. how to achieve this.
service.ts code is given below
empservicecall() {
return this.http.get("http://localhost:3000/api/Employee")
}
component.ts code is given below
GetEmpName(){
this.Emp.empservicecall()
.subscribe(
response =>{
this.name=response.json})
}
it is not working and also error is coming in this code at line response.json().
plz help me

The solution to your issue completely depends on which version of Angular you are on and whether you're using Http or HttpClient.
If you're using HttpClient, then:
empservicecall() {
return this.http.get("http://localhost:3000/api/Employee");
}
And in your Component:
GetEmpName(){
this.Emp.empservicecall()
.subscribe(response => {
console.log(response);
this.name = response[0].name
});
}
If you're using Http(which has been deprecated after the introduction of HttpClient in Angular 4.3 BTW), then:
import 'rxjs/add/operator/map';
empservicecall() {
return this.http.get("http://localhost:3000/api/Employee")
.map((res: any) => res.json());
}
And in your Component:
GetEmpName(){
this.Emp.empservicecall()
.subscribe(response => {
console.log(response);
this.name = response[0].name
});
}

Related

Angular Unexpected token c in JSON at position 0 at JSON.parse when expecting a string

I am not sure what I am doing wrong here.
I am trying to use the checkout facility for stripe using this documentation: https://stripe.com/docs/payments/checkout/accept-a-payment
I have configured my API to just return the checkoutid as a string.
The Angular service just calls the controller. When I run my code I actually get a nice 200 response and I can see the checkout id in the response body, but Angular throws an error:
SyntaxError: Unexpected token c in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad (https://127.0.0.1:4200/vendor.js:18780:51) at ZoneDelegate.invokeTask
The service looks like this:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { map } from 'rxjs/operators';
import { environment } from '#environments/environment';
#Injectable({
providedIn: 'root',
})
export class StripeService {
private endpoint: string = 'stripe';
constructor(private http: HttpClient) {}
checkout(priceId: string) {
return this.http
.get<string>(`${environment.apiUrl}/${this.endpoint}/${priceId}`)
.pipe(
map((response) => {
console.log(response);
return response;
})
);
}
}
and I am invoking it like this:
this.stripeService
.checkout(this.button.priceId)
.subscribe((checkoutId: string) => {
console.log(checkoutId);
// this.stripe
// .redirectToCheckout({
// sessionId: checkoutId,
// })
// .then(function (result) {
// // If `redirectToCheckout` fails due to a browser or network
// // error, display the localized error message to your customer
// // using `result.error.message`.
// });
});
If I look in the network tab I can see this:
But the console actually shows this:
Does anyone have a scooby why?
Probably the response is a string and you haven't specified the response type. Try the following
this.http.get(
`${environment.apiUrl}/${this.endpoint}/${priceId}`,
{ responseType: 'text' }
)
Default response type is json.
It happened to me when my API return doesent match with my deserializable object on Angular. At first, try to check your returns entities

How to convert json to JSONP after it json load as a subscription in angular?

I want to make a call with jsonp but i have json data as a subscription
my service.ts file:-
gridUrl = 'https://jsonplaceholder.typicode.com/posts';
getGrid() {
return this.http.get<Grid>(this.gridUrl, httpOptions);
}
and in my component.ts
grid: Grid;
grids: any;
showGrid() {
this.gridService.getGrid()
.subscribe(
gridData => this.grids = gridData
);
}
That above code is working fine and gives me data in grids variable as a json
But I need to use that json data in below code .
private fetch(action: string = '', data?: any): Observable<any[]> {
return this.http
.jsonp(`https://jsonplaceholder.typicode.com/posts/${action}?${this.serializeModels(data)}`, 'callback')
.pipe(map(res => <any[]>res));
}
How would I do that?

Unble to Extract the _body response in angular 4 in JSON format

I am using angular 4.2.6 for my application. I have a service like this
checkStaff(email: any) {
return this._http.post(this.url + "/Impsapi/getStaff", JSON.stringify(email)).map(
(resp) => resp
)
}
checkStaff(email:any){
return
this._http.post(this.url+"/Impsapi/getStaff",JSON.stringify(email)).map(
(resp)=> resp
)
}
this.loginServ.checkStaff(this.user)
.subscribe(
userData => {
this._return = userData;
console.log(this._return);
}
);
The Server returns JSON as response. but when i log the output, i get the below
logged response
please I need to consume the data in the body of the response. I have not been able convert the ._body to a proper json and use for the app. please help
The response data are in JSON string form. The app must parse that string into JavaScript objects by calling res.json().
return this._http.post(this.url + "/Impsapi/getStaff", JSON.stringify(email)).map(
(resp) => resp.json()
)
Update
try following code snippet
checkStaff(email: any) {
return this._http.post(this.url + "/Impsapi/getStaff", JSON.stringify(email))
.map(res => {return res.json()})
}
Try this:
this.loginServ.checkStaff(this.user)
.subscribe(
userData => {
this._return = userData.json();
console.log(this._return);
}
);
I mean your checkStaff:
checkStaff(email: any): Observable<Response> {
return this._http.post(this.url + "/Impsapi/getStaff", JSON.stringify(email));
}
export classMyResp
{
id: string;
/*so on...*/
}
This will give you the body of response If there is any.
I got my problem solved. My PHP is hosted on wampserver. In a way invalid JSON is always returned when i make call to the server. I had to use the ob_clean() function and everything is fine.

What does "Result" means in a .map operator of an Observable obtained from an http.get request in nativescript/angular

I'm doing the nativescript/angular tutorial and I found something in the code that I don't understand and want some clarification.
In chapter 4 (Nativescript modules) when they do a http.get resquest to retrieve the Grocery List and they get the Observable I notice that it is passed throught some maps operator, here is the code:
import { Injectable } from "#angular/core";
import { Http, Headers } from "#angular/http";
import { Observable } from "rxjs/Rx";
import "rxjs/add/operator/map";
import { Config } from "../config";
import { Grocery } from "./grocery";
#Injectable()
export class GroceryListService {
constructor(private http: Http) {}
load() {
let headers = new Headers();
headers.append("Authorization", "Bearer " + Config.token);
return this.http.get(Config.apiUrl + "Groceries", {
headers: headers
})
.map(res => res.json())
.map(data => {
let groceryList = [];
data.Result.forEach((grocery) => { //<------HERE
groceryList.push(new Grocery(grocery.Id, grocery.Name));
});
return groceryList;
})
.catch(this.handleErrors);
}
handleErrors(error: Response) {
console.log(JSON.stringify(error.json()));
return Observable.throw(error);
}
}
My question is, what does "Result" means in the second .map
Why they don't simply put
data.forEach((grocery) => {
I ask because I'm not sure if it is an object property of the resulting observable from .map(res => res.json) or something else.
Could you point me to some documentation of where does that "Result" come from and what it means?
First of all, this line .map(res => res.json()) parses the response body into a json object. Then the second map allows access to this json object under data argument. The json object represented by data is actually a wrapper around the actual response result data using the Result as the key mapped to the data returned from the backend which follows this security advise HERE. So data.Result is just a key mapped to the actual data returned from the backend. The backend could have used a different name for the key, e.g. secret, then you would do data.secret to obtain the data returned from the server

Ionic2 and get Json

I am trying to use Ionic2 and I made a service to fetch a local stored Json.
import {Injectable} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
#Injectable()
export class Page1Service {
public constructor(private _http: Http) {}
public GetItems() {
return this._http.get('/app/Ressources/Items.json').map((response: Response) => response.json().data);
}
public PrintJson():boolean {
var myresult;
this.GetItems().subscribe((result) => {
myresult = result;
console.log(result);
});
}
I also a made PrintJson() method that just print the json for test purpose.I got the error:
GET http://localhost:8100/app/Ressources/slides.json 404 (Not Found)
I don't get why. And I can't find an easy and uptodate tutorial. Or should I use fetch()?
First copy your json to the following dir(you can create the folder "data"):
[appname]/www/data/data.json
Type in the following command in your console:
ionic g provider JsonData
It should create a provider for you.Go to that page and enter the following in load() function:
load() {
if (this.data) {
// already loaded data
return Promise.resolve(this.data);
}
// don't have the data yet
return new Promise(resolve => {
// We're using Angular Http provider to request the data,
// then on the response it'll map the JSON data to a parsed JS object.
// Next we process the data and resolve the promise with the new data.
this.http.get('data/data.json').subscribe(res => {
// we've got back the raw data, now generate the core schedule data
// and save the data for later reference
this.data = res.json();
resolve(this.data);
console.log(this.data);
});
});
}
I usually create an Observable wrapped around the api-call like this:
public GetItems() {
return Observable.create(observer => {
this._http.get('/app/Ressources/Items.json').map(res =>res.json()).subscribe(data=>{
observer.next(data)
observer.complete();
});
});
}
Then I have to subscribe on that method in order to get the results and do something with it. (You could be to delegate the result to a list in the GUI)
GetItems().subscribe(data=>{
myResult = data;
});
EDIT: It might help to put this in the class as well
export class MyClass{
static get parameters(){
return [[Http]];
}
}
Just try to get the response.json() rather than response.json().data in GetItems() method
The issue is because of different paths of json files in local browser(computer) and device (android). Create data folder inside the src\assets folder. Move your json file into that.
When we run ionic serve, it will move that folder (with file) into www\assets folder. Then do following things:
Import Platform service of ionic2
import { Platform } from 'ionic-angular';
Inject Platform Service.
constructor(private http: Http, private platform: Platform ) { }
Use Platform Service.
public getItems() {
var url = 'assets/data/Items.json';
if (this.platform.is('cordova') && this.platform.is('android')) {
url = "/android_asset/www/" + url;
}
return this.http.get(url)
.map((res) => {
return res.json()
});
}