角度4中的HTTP和HTTPClient之间的区别? [英] Difference between HTTP and HTTPClient in angular 4?

查看:170
本文介绍了角度4中的HTTP和HTTPClient之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道用哪个来构建模拟Web服务来测试Angular程序?

I want to know which one to use to build a mock web service to test the Angular program?

推荐答案

使用 HttpClient 来自 HttpClientModule 的课程,如果您使用的是Angular 4.3.x及以上版本:

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是假设的默认值,不再需要显式解析

  • 请求后验证&基于刷新的测试框架

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

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

还要注意使用 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我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',

这篇关于角度4中的HTTP和HTTPClient之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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