角度4中的HTTP和HTTPClient之间的区别?
如果你使用4.3.x版角及以上使用来自HttpClientModule
的HttpClient
类:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
HttpClientModule
],
...
class MyService() {
constructor(http: HttpClient) {...}
这是一个从@angular/http
模块的http
的升级版具有以下改进:
- 拦截器允许中间件逻辑插入流水线
- 不可变的请求/响应ob jects
- 两个要求上传和响应进度事件下载
您可以了解它是如何工作的Insider’s guide into interceptors and HttpClient mechanics in Angular。
- 类型化,同步响应体访问,包括JSON体类型
- JSON载体是假定默认和不再需要显式地解析
- 后请求验证&平齐基于测试框架
继续前进旧的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
,所以你必须安装它npm i tslib
和更新system.config.js
如果你使用SystemJS
:
map: {
...
'tslib': 'npm:tslib/tslib.js',
而你需要,如果你使用SystemJS添加另一个映射:
'@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',
我想导入HttpClientModule。但'@ angular/common/http'不存在于使用“npm start”命令安装的node_modules目录中。你能帮我吗? –
@DheerajKumar,你使用的是哪个版本?它只在4.3.0以上可用 –
我从git下载了角度快速启动。和在package.json中,“@ angular/common”:“^ 4.3.0”存在。但没有@ angular/common/http。 –
不想重复,只是在其他的方式总结:
-
从JSON的一个对象
- 自动转换
- 响应类型定义
- 事件引发
- 标题的简化语法
- 拦截器
我写了一篇文章,介绍了旧的“http”和新的“HttpClient”之间的区别。目标是以最简单的方式解释它。
[* “的HttpClient是现有的角HTTP API,它存在 它沿着在一个单独的封装的进化...” *](https://github.com/angular/angular /提交/ 37797e2)。 – jonrsharpe
昨天我在博客上写了一些新功能:http://blog.jonrshar.pe/2017/Jul/15/angular-http-client.html – jonrsharpe
https://angular.io/guide/http – yurzui