HttpModule 和 HttpClientModule 的区别 [英] Difference between HttpModule and HttpClientModule

查看:25
本文介绍了HttpModule 和 HttpClientModule 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用哪个来构建模拟 Web 服务来测试 Angular 4 应用程序?

Which one to use to build a mock web service to test the Angular 4 app?

推荐答案

如果您使用的是 Angular 4.3.x 及更高版本,请使用 HttpClientModule 中的 HttpClient 类:

Use the HttpClient class from HttpClientModule if you're using Angular 4.3.x and above:

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

@NgModule({
 imports: [
   BrowserModule,
   HttpClientModule
 ],
 ...

 class MyService() {
    constructor(http: HttpClient) {...}

它是 @angular/http 模块中 http 的升级版本,具有以下改进:

It's an upgraded version of http from @angular/http module with the following improvements:

  • 拦截器允许将中间件逻辑插入管道
  • 不可变的请求/响应对象
  • 请求上传和响应下载的进度事件

您可以在 Angular 中拦截器和 HttpClient 机制的内幕指南.

  • 类型化的同步响应正文访问,包括对 JSON 正文类型的支持
  • JSON 是假定的默认值,不再需要显式解析
  • 请求后验证和基于flush的测试框架

继续使用旧的 http 客户端将被弃用.以下是提交消息官方文档.

Going forward the old http client will be deprecated. Here are the links to the commit message and the official docs.

还要注意旧的 http 是使用 Http 类令牌而不是新的 HttpClient 注入的:

Also pay attention that old http was injected using Http class token instead of the new HttpClient:

import { HttpModule } from '@angular/http';

@NgModule({
 imports: [
   BrowserModule,
   HttpModule
 ],
 ...

 class MyService() {
    constructor(http: Http) {...}

另外,新的 HttpClient 在运行时似乎需要 tslib,所以你必须安装它 npm i tslib 并更新 system.config.js 如果你使用 SystemJS:

Also, new HttpClient seem to require tslib in runtime, so you have to install it npm i tslib and update system.config.js if you're using SystemJS:

map: {
     ...
    'tslib': 'npm:tslib/tslib.js',

如果使用 SystemJS,则需要添加另一个映射:

And you need to add another mapping if you use SystemJS:

'@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',

这篇关于HttpModule 和 HttpClientModule 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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