use angular 2 data from rest api - json

I'm begining in Angular 2 , in the first I try to get data from JSON file and show it on a table and that's done , now I want to get data from rest api so I create my Restful webservices from Entity classes , I generate the CrossOriginResourceSharingFilter ( I use netbeans and glassfish) and I get the link with JSON output , I replace the link in the api url in angular 2 but it doesn't work
this in my Angular 2 employes.service
#Injectable()
export class EmployesService {
private empsUrl = 'localhost:25176/WebApplication4/app/employes'; // URL to web api
constructor(private http: Http) { }
getEmployes (){
return this.http.get(this.empUrl)
.map(res=> res.json())
.catch(this.handleError);
}
this is my employes.component
export class EmployesComponent implements OnInit{
emps: Employe[];
error: any;
mode = 'Observable';
errorMessage :string;
constructor(private empService: EmployesService,private _elRef :ElementRef) { }
getEmployes() {
this.empService.getEmployes()
.subscribe(
employes => this.emps = employes,
error => this.errorMessage = <any>error);
}
ngOnInit() {
this.getEmployes();
this is my console Errors
zone.js:101 XMLHttpRequest cannot load localhost:25176/WebApplication4/app/employes. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
thank you for helping

Related

Typescript (Angular) - JSON model Deserialisation

I would like to add and populate additional fields (which are not sent by backend service) in my http model. Catch is that I am not able to populate (map) those fields in the place where http response is being received since I am using internal framework.
Is there a possibility in Typescript (Angular) to somehow override JSON Deserialisation flow/Instance creation and populate mentioned fields. For example:
interface ElectricDevice {
energy_meter_start: number; // received from backend service
energy_meter_stop: number; // received from backend service
energy_spent: number; // not received by backend service, but needs to be populated as energy_meter_stop - energy_meter_start
// ...
/* I would like to somehow populate energy_spent as energy_meter_stop-energy_meter_end on instance creation (deserialisation) */
}
You need a HttpInterceptor, in which you can manipulate data.
#Injectable()
export class CustomJsonInterceptor implements HttpInterceptor {
constructor(private jsonParser: JsonParser) {}
intercept(httpRequest: HttpRequest<any>, next: HttpHandler) {
if (httpRequest.responseType === 'json') {
// If the expected response type is JSON then handle it here.
return this.handleJsonResponse(httpRequest, next);
} else {
return next.handle(httpRequest);
}
}
Read more about it in the tutorials: https://angular.io/api/common/http/HttpInterceptor
I have asked you for the especific names of your services.
But, in the meantime, I give you a 'general' answer to your question.
You just need to do this:
this.yourService.yourGetElectriceDevices
.pipe(
map (_resp: ElectricDevice => _resp.energy_spent = _resp.energy_meter_stop - _resp.energy_meter_start
)
.subscribe( resp => { //your treatment to the response });
This above, only works for a rapid test.
If you want to do somethig more 'elaborated', you could transform your interface into a class, and add your calculated attribute, something like this:
export interface ElectricDevice {
energy_meter_start: number; // received from backend service
energy_meter_stop: number; // received from backend service
}
export Class ElectricDeviceClass {
energy_meter_start: number;
energy_meter_stop: number;
energy_spent: number;
constructor (data: ElectricDevice) {
this.energy_meter_start = data.energy_meter_start;
this.energy_meter_stop= data.energy_meter_stop;
this.energy_spent = this.energy_meter_stop - this.energy_meter_start;
}
And for using it, just:
import { ElectricDeviceClass, ElectricDevice } from './../model/...' // There where you have yours interfaces and model classes
this.yourService.yourGetElectriceDevices
.pipe(
map (_resp: ElectricDevice => new ElectricDeviceClass(_resp)
)
.subscribe( resp => { //your treatment to the response });

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 intercept call and serve back JSON file dynamically (without "import")

I have a scaffolding of folders and json files to mock an API's paths. When I run npm run start:mock, LocalMockInterceptor gets provisioned and e.g. replaces a call to host/A/B/C by an http call getting locally Folder A/Folder B/C.json. The JSON files get produced by a separate script which is out of scope here. I cannot make use of "import" as many tutorials show because I need a generic solution as the API i am mocking will evolve over time (and so will this scaffolding of folders and files).
/**
* The idea is to only build this into the bundle if we specify so (e.g. on TeamCity, on your localhost), where you don't want to rely
* on external resources for development
* No conditionals in the code bundle! No configuration files or database dependency.
*/
import {
HttpInterceptor,
HttpResponse,
HttpHandler,
HttpRequest,
HttpEvent,
HttpClient,
HttpHeaders
} from '#angular/common/http';
import { Injectable, Injector } from '#angular/core';
import { Observable, of } from 'rxjs';
import { ErrorService } from './error.service';
const devAssetsFolder = 'assets';
#Injectable()
export class LocalMockInterceptor implements HttpInterceptor {
constructor(
private errorService: ErrorService,
private injector: Injector,
private http: HttpClient
) {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
if (request.url.endsWith('.json')) return next.handle(request);
console.log(
` >>> Mock Interceptor >>> ${request.url} has been intercepted`
);
const path = `${devAssetsFolder}${request.url}.json`;
var promise = this.getJSON(path).toPromise();
const jsonheaders = new HttpHeaders();
jsonheaders.set('Content-Type', 'application/json');
let json2;
promise
.then(json => {
console.log(json);
json2 = json;
})
.catch(error => console.log(error));
Promise.all([promise]);
console.log(json2);
return of(
new HttpResponse({ status: 200, body: json2, headers: jsonheaders })
);
}
private getJSON(jsonPath: string): Observable<any> {
return this.http.get(jsonPath);
}
}
The first conditional is to avoid infinite loops since I am sending HTTP requests in my interceptor
Getting the path to the JSON file based on the URL is quite natural
It seemed to me that I have to convert the JSON Observable into a promise so that I can wait for it to complete before rewrapping that json into the returned Observable. When debugging however, it seems Promise.all is not waiting for the promise to complete (json2 is undefined on the next line), and I end up sending an empty http body back...
How to fix this rxjs promise ?
Is inner HTTP calls my only option ?
Is there a way not to rely on promises ? Can you think of a better way to achieve this ?
Did you try just modifying the target URL in your interceptor ? You want to make an API call that return some JSON but instead of calling a dynamic API, you just want to call you static server so it can return predefined JSON.
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const fakeUrl = `${devAssetsFolder}${request.url}.json`;
const fakeRequest = request.clone({url: fakeUrl});
return next.handle(request);
}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
if (request.url.endsWith('.json')) return next.handle(request);
console.log(
` >>> Mock Interceptor >>> ${request.url} has been intercepted`
);
const path = `${devAssetsFolder}${request.url}.json`;
return this.getJSON(path).pipe(map(result => {
const jsonheaders = new HttpHeaders({ 'Content-Type': 'application/json' });
return
new HttpResponse({ status: 200, body: result, headers: jsonheaders });
}), // you can also add catchError here
);
}
In intercept method you can return an observable. So your getJSON method returns an observable, we added pipe a map function which maps the result to new http response. If your response already has the right headers you don't even need the pipe and map functions you can just do this :
return this.getJSON(path); // it's an observable, so it's OK.

Add new object to local json file in Angular 4

I have a simple method to call the json file located in my assets folder
private jsonPath = '../assets/data/sample.json';
constructor(private http: Http) {
http.get(this.jsonPath)
.subscribe(response => {
this.posts = response.json();
})
Works well on reading it however I want to perform CRUD operation on it (for example create a new object). Is it possible to do?

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