我正在try 将以下Angular 1代码转换为Angular 2:
$http.jsonp('https://accounts.google.com/logout');
它需要是一个JSONP请求来跳过CORS策略问题.
我正在try 将以下Angular 1代码转换为Angular 2:
$http.jsonp('https://accounts.google.com/logout');
它需要是一个JSONP请求来跳过CORS策略问题.
In the latest version of Angular
在应用程序模块的定义文件中导入HttpClientModule和HttpClientJsonpModule个模块
import {
HttpClientModule,
HttpClientJsonpModule
} from '@angular/common/http';
@NgModule({
declarations: [
//... List of components that you need.
],
imports: [
HttpClientModule,
HttpClientJsonpModule,
//...
],
providers: [
//...
],
bootstrap: [AppComponent]
})
将http和map rxjs运营商注入您的服务:
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class MegaSuperService {
constructor(private _http: HttpClient) {}
}
以以下方式发出JSONP请求:
// inside your service
this._http.jsonp('/api/get', 'callback').map(data => {
// Do stuff.
});
In Angular version 2 - version 4.3
在应用程序模块的定义文件中导入JSONP模块:
import {JsonpModule} from '@angular/http';
@NgModule({
declarations: [
//... List of components that you need.
],
imports: [
JsonpModule,
//...
],
providers: [
//...
],
bootstrap: [AppComponent]
})
向您的服务中注入jsonp服务和map rxjs运营商:
import {Injectable} from '@angular/core';
import {Jsonp} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class MegaSuperService {
constructor(private _jsonp: Jsonp) {}
}
使用"JSONP_回调"作为回调属性发出请求:
// inside your service
this._jsonp.get('/api/get?callback=JSONP_CALLBACK').map(data => {
// Do stuff.
});