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.
In the latest version of Angular
Import HttpClientModule and HttpClientJsonpModule modules in your app module's definition file
import {
HttpClientModule,
HttpClientJsonpModule
} from '@angular/common/http';
@NgModule({
declarations: [
//... List of components that you need.
],
imports: [
HttpClientModule,
HttpClientJsonpModule,
//...
],
providers: [
//...
],
bootstrap: [AppComponent]
})
Inject http and map rxjs operator into your service into your service:
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class MegaSuperService {
constructor(private _http: HttpClient) {}
}
Make JSONP requests in the following way:
// inside your service
this._http.jsonp('/api/get', 'callback').map(data => {
// Do stuff.
});
In Angular version 2 - version 4.3
Import JSONP module in your app module's definition file:
import {JsonpModule} from '@angular/http';
@NgModule({
declarations: [
//... List of components that you need.
],
imports: [
JsonpModule,
//...
],
providers: [
//...
],
bootstrap: [AppComponent]
})
Inject jsonp service and map rxjs operator into your service:
import {Injectable} from '@angular/core';
import {Jsonp} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class MegaSuperService {
constructor(private _jsonp: Jsonp) {}
}
Make requests using "JSONP_CALLBACK" as a callback property:
// inside your service
this._jsonp.get('/api/get?callback=JSONP_CALLBACK').map(data => {
// Do stuff.
});