Using JSONP Service in angular2

Using JSONP Service in angular2

Hi Guys , It seems this is my first angular2 post, even though I am using it in my ionic2 but I dont think it should matter since everything is the same .

So here is the plan : I want to use github api ( you can also use jsonplaceholder api ) and fetch json object of all jobs using http.

But There is a problem , Since browsers have same origin policy , meaning that http request from a server to a different server are not possible , so we cannot use HTTP , Instead we can use JSONP, I never used JSONP API Before , but its actually pretty simple

So Let’s Get started!

Create a blank new angular2 project

Create a new provider called data ( This will serve as our data service )

So few comments regarding the code below , First we will import required “stuff” In this case JSONP,Response,Headers etc. Also notice we are importing Observables because thats how we are going to handle our async responses.
You can find the basic boilerplate code at angular2 website.

Now notice that I have created a new member variable url of the class and in its original url value I have appended callback=JSON_CALLBACK , well this is because we are dealing with JSONP and when we get our response back our JSONP_CALLBACK will be fired.

We are also making use of rxjs map and catch operator. map will basically map our chunk of data to json . So thats it for the service , nothing very groundbreaking here


import { Http,Jsonp, Response } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

import 'rxjs/add/observable/throw';

import {Injectable} from '@angular/core';

@Injectable()
export class DataService {

private url :any ="https://jobs.github.com/positions.json?description=python&location=new+york&callback=JSONP_CALLBACK";

constructor(private jsonp:Jsonp){

}

getdata() : Observable {

return this.jsonp.get(this.url)
.map(this.extractData)
.catch(this.handleError);

}

private extractData(res: Response) {
let body = res.json();

console.log('extracting data');

return body ;

}

private handleError (error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error('err' + errMsg); // log to console instead
return Observable.throw(errMsg);
}

}

Okay So now lets “consume” our data service , So Either can use your current component, or create a new one and import the Service.

So my homepage.ts file looks something like this :

import {DataService} from '../../providers/data/data';

@Component({
templateUrl: 'build/pages/home/home.html',
providers:[DataService]

})
export class HomePage {

public data:any;
private errorMessage:any;

constructor(private dataService:DataService) {

this.dataService.getdata()
.subscribe(
data => this.data = data,
error => this.errorMessage = error);

}

}

So since we now have the data we can actually use this by interpolation and using the json pipe for clarity .

Data

{{data | json }}

That should be it , You should see the resulting json 🙂