nunoarruda nunoarruda - 1 year ago 242
TypeScript Question

How to make a simple JSONP asynchronous request in Angular 2?

I'm trying to convert the following Angular 1 code to Angular 2:


It needs to be a JSONP request to skip the CORS policy issue.

Answer Source

If this endpoint is jsonp-compliant, you can use the following. You need to find out the parameter to use to provide the jsonp callback. In the code below, I call it c.

After having registered JSONP_PROVIDERS when calling the bootstrap function:

import {bootstrap} from 'angular2/platform/browser'
import {JSONP_PROVIDERS} from 'angular2/http'
import {AppComponent} from './app.component'

bootstrap(AppComponent, [ JSONP_PROVIDERS ]);

You can then execute your request using an instance of the Jsonp class you injected from constructor:

import {Component} from 'angular2/core';
import {Jsonp} from 'angular2/http';

  selector: 'my-app',
  template: `
      Result: {{result | json}}
export class AppComponent {
  constructor(jsonp:Jsonp) {
    var url = '';
    jsonp.request(url, { method: 'Get' })
     .subscribe((res) => {

See this question for more details: