如果你使用的是Angular 4.3,请使用HttpClientModule
中的HttpClient
类.x及以上:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
HttpClientModule
],
...
class MyService() {
constructor(http: HttpClient) {...}
它是从@angular/http
模块升级到http
的版本,有以下改进:
- 拦截器允许将中间件逻辑插入到管道中
- 不可变的请求/响应对象
- 请求上载和响应下载的进度事件
你可以在Insider’s guide into interceptors and HttpClient mechanics in Angular里读到它是如何工作的.
- 类型化、同步响应主体访问,包括对JSON主体类型的支持
- JSON是假定的默认值,不再需要显式解析
- 请求后验证&;基于flush的测试框架
今后,旧的http客户端将被弃用.以下是commit message和the official docs的链接.
还要注意,旧的http是使用Http
类令牌而不是新的HttpClient
类令牌注入的:
import { HttpModule } from '@angular/http';
@NgModule({
imports: [
BrowserModule,
HttpModule
],
...
class MyService() {
constructor(http: Http) {...}
此外,新HttpClient
在运行时似乎需要tslib
,所以如果使用SystemJS
,则必须安装npm i tslib
并更新system.config.js
:
map: {
...
'tslib': 'npm:tslib/tslib.js',
如果您使用SystemJS,则需要添加另一个映射:
'@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',