nunoarruda nunoarruda - 1 month ago 89
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:

$http.jsonp('https://accounts.google.com/logout');


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

Answer

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';

@Component({
  selector: 'my-app',
  template: `
    <div>
      Result: {{result | json}}
    </div>
  `
})
export class AppComponent {
  constructor(jsonp:Jsonp) {
    var url = 'https://accounts.google.com/logout&c=JSONP_CALLBACK';
    jsonp.request(url, { method: 'Get' })
     .subscribe((res) => {
       (...)
     });
  }
}

See this question for more details: