How to use Angular 2 JSONP

Currently I am working on personal project that using Angular 2 consumes World Bank APIs. Fortunately World Bank API supports JSONP, so I do not need to wrap those APIs into my own server side code.

Since I am new to Angular 2 and JSONP, I did encounter problems, and I want to share those problems and solution.

1. What is JSONP?

Based on my understand, JSONP wraps Json repsonse into a javascript callback method, which allows your front-end code bypass cross domain ajax restriction. For instance, request URL is

www.example.net/sample.aspx?callback=myCallBack

and response json suppose like

{"id":100}

By using JSONP what you actually return is like

myCallBack = function(responseJson){  
console.log(responseJson); // output: {"id":100}
}

2. Use JSONP in Angular 2

  • Config App Bootstrap
import { HTTP_PROVIDERS, JSONP_PROVIDERS } from '@angular/http';
bootstrap(AppComponent, [JSONP_PROVIDERS])

So if you add JSONP_PROVIDERS in your bootstrap, then in any component you are going to work with, you do need to explicitly add into your Component decorator provider.

  • In Service (/services/worldBankHttpService.ts)
import {Injectable} from "@angular/core";  
import {Http, Response, Jsonp} from "@angular/http";
import {Observable} from "rxjs/Rx";
@Injectable()
export class WorldBankService{
constructor(private jsonp:Jsonp){}
    private url = "http://api.worldbank.org/countries/us/indicators/SH.XPD.PRIV.ZS?date=2000:2002&format=jsonP&prefix=JSONP_CALLBACK";
    getTestData(): Observable<any[]>{
return this.jsonp.get(this.url)
.map(function(res: Response){
return res.json() || {};
}).catch(function(error: any){return Observable.throw(error);
});
}
}

So if we take a look at URL here, in the very end, there is prefix=JSONPCALLBACK, so the value JSONPCALLBACK is the function that contains response data from Angular Jsonp service, like I mentioned above. So it will becomeres: Response in the map callback.

  • Finally just use this service like as Angular services.

Source code link