Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

typescript - 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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In the latest version of Angular

  1. 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]
     })
    
  2. Inject http and map rxjs operator 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) {}
     }
    
  3. 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

  1. 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]
     })
    
  2. 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) {}
     }
    
  3. Make requests using "JSONP_CALLBACK" as a callback property:

     // inside your service
     this._jsonp.get('/api/get?callback=JSONP_CALLBACK').map(data => {
     // Do stuff.
     });
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...