如何在 Angular 2 中进行简单的 JSONP 异步请求? [英] How to make a simple JSONP asynchronous request in Angular 2?

查看:30
本文介绍了如何在 Angular 2 中进行简单的 JSONP 异步请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将以下 Angular 1 代码转换为 Angular 2:

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

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

必须是 JSONP 请求才能跳过 CORS 政策问题.

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

推荐答案

在最新版的Angular

  1. 在应用模块的定义文件中导入HttpClientModuleHttpClientJsonpModule 模块

 import {
     HttpClientModule,
     HttpClientJsonpModule
 } from '@angular/common/http';

 @NgModule({
 declarations: [
     //... List of components that you need.
 ],
 imports: [
     HttpClientModule,
     HttpClientJsonpModule,
     //...
 ],
 providers: [
     //...
 ],
 bootstrap: [AppComponent]
 })

  • httpmap rxjs 操作符注入您的服务:

  • 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) {}
     }
    

  • 以下列方式发出 JSONP 请求:

  • Make JSONP requests in the following way:

     // inside your service
     this._http.jsonp('/api/get', 'callback').map(data => {
     // Do stuff.
     });
    

  • Angular 2 - 4.3 版

    1. 在应用模块的定义文件中导入 JSONP 模块:

    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]
     })
    

  • jsonp 服务和 map rxjs 操作符注入到您的服务中:

  • 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) {}
     }
    

  • 使用JSONP_CALLBACK"发出请求作为回调属性:

  • Make requests using "JSONP_CALLBACK" as a callback property:

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

  • 这篇关于如何在 Angular 2 中进行简单的 JSONP 异步请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆