安装

首先,我们需要更新所有的包到 4.3.0-rc.0 版本。然后,我们需要在 AppModule 中导入 HttpClientModule 模块。具体如下:

import { HttpClientModule } from '@angular/common/http';
@NgModule({declarations: [AppComponent],imports: [BrowserModule,HttpClientModule],bootstrap: [AppComponent]
})
export class AppModule { }

现在一切准备就绪。让我们来体验一下我们一直期待的三个新特性。

特性一 默认 JSON 解析

现在 JSON 是默认的数据格式,我们不需要再进行显式的解析。即我们不需要再使用以下代码:

http.get(url).map(res => res.json()).subscribe(...)

现在我们可以这样写:

http.get(url).subscribe(...)

特性二 支持拦截器 (Interceptors)

拦截器允许我们将中间件逻辑插入管线中。

请求拦截器 (Request Interceptor)

import {HttpRequest,HttpHandler,HttpEvent
} from '@angular/common/http';@Injectable()
class JWTInterceptor implements HttpInterceptor {constructor(private userService: UserService) {}intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {const JWT = `Bearer ${this.userService.getToken()}`;req = req.clone({setHeaders: {Authorization: JWT}});return next.handle(req);}
}

如果我们想要注册新的拦截器 (interceptor),我们需要实现 HttpInterceptor 接口,然后实现该接口中的 intercept 方法。

export interface HttpInterceptor {intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>;
}

需要注意的是,请求对象和响应对象必须是不可修改的 (immutable)。因此,我们在返回请求对象前,我们需要克隆原始的请求对象。

next.handle(req) 方法使用新的请求对象,调用底层的 XHR 对象,并返回响应事件流。

响应拦截器 (Response Interceptor)

@Injectable()
class JWTInterceptor implements HttpInterceptor {constructor(private router: Router) {}intercept(req: HttpRequest < any > ,next: HttpHandler): Observable < HttpEvent < any >> {return next.handle(req).map(event => {if (event instanceof HttpResponse) {if (event.status === 401) {// JWT expired, go to login}}return event;}}
}

响应拦截器可以通过在 next.handle(req) 返回的流对象 (即 Observable 对象) 上应用附加的 Rx 操作符来转换响应事件流对象。

接下来要应用 JWTInterceptor 响应拦截器的最后一件事是注册该拦截器,即使用 HTTP_INTERCEPTORS 作为 token,注册 multi Provider:

[{ provide: HTTP_INTERCEPTORS, useClass: JWTInterceptor, multi: true }]

特性三 进度事件 (Progress Events)

进度事件可以用于跟踪文件上传和下载。

import {HttpEventType,HttpClient,HttpRequest
} from '@angular/common/http';http.request(new HttpRequest('POST',URL,body, {reportProgress: true})).subscribe(event => {if (event.type === HttpEventType.DownloadProgress) {// {// loaded:11, // Number of bytes uploaded or downloaded.// total :11 // Total number of bytes to upload or download// }}if (event.type === HttpEventType.UploadProgress) {// {// loaded:11, // Number of bytes uploaded or downloaded.// total :11 // Total number of bytes to upload or download// }}if (event.type === HttpEventType.Response) {console.log(event.body);}
})

如果我们想要跟踪文件上传或下载的进度,在创建请求对象时,我们需要配置 {reportProgress: true} 参数。

此外在回调函数中,我们通过 event.type 来判断不同的事件类型,从进行相应的事件处理。

HttpEventType 枚举定义如下:

export enum HttpEventType {/*** 表示请求已经被发送*/Sent,/*** 已接收到上传进度事件*/UploadProgress,/*** 已接收到响应状态码和响应头*/ResponseHeader,/*** 已接收到下载进度事件*/DownloadProgress,/*** 已接收全部响应,包含响应体 */Response,/*** 用户自定义事件,来自拦截器或后端*/User,
}

其实除了上面介绍三个新的功能之外,还有以下两个新的功能:

  • 基于 Angular 内部测试框架的 Post-request verification 和 flush 功能

  • 类型化,同步响应体访问,包括对 JSON 响应体类型的支持。

最后我们来通过 client_spec.ts 文件中的测试用例,来进一步感受一下上述的新特性。

其它特性

发送 GET 请求

describe('HttpClient', () => {let client: HttpClient = null !;let backend: HttpClientTestingBackend = null !;beforeEach(() => {backend = new HttpClientTestingBackend();client = new HttpClient(backend);});afterEach(() => { backend.verify(); }); // 请求验证describe('makes a basic request', () => {it('for JSON data', (done: DoneFn) => {client.get('/test').subscribe(res => {expect((res as any)['data']).toEqual('hello world');done();});backend.expectOne('/test').flush({'data': 'hello world'});});it('for an arraybuffer', (done: DoneFn) => {const body = new ArrayBuffer(4);// 还支持 {responseType: 'text'}、{responseType: 'blob'}client.get('/test', {responseType: 'arraybuffer'}).subscribe(res => {expect(res).toBe(body);done();});backend.expectOne('/test').flush(body);});it('that returns a response', (done: DoneFn) => {const body = {'data': 'hello world'};client.get('/test', {observe: 'response'}).subscribe(res => {expect(res instanceof HttpResponse).toBe(true);expect(res.body).toBe(body);done();});backend.expectOne('/test').flush(body);});});
});

发送 POST 请求

describe('makes a POST request', () => {it('with text data', (done: DoneFn) => {client.post('/test', 'text body', {observe: 'response', responseType: 'text'}).subscribe(res => {expect(res.ok).toBeTruthy();expect(res.status).toBe(200);done();});backend.expectOne('/test').flush('hello world');});it('with json data', (done: DoneFn) => {const body = {data: 'json body'};client.post('/test', body, {observe: 'response', responseType: 'text'}).subscribe(res => {expect(res.ok).toBeTruthy();expect(res.status).toBe(200);done();});const testReq = backend.expectOne('/test');expect(testReq.request.body).toBe(body);testReq.flush('hello world');});
});

发送 JSONP 请求

describe('makes a JSONP request', () => {it('with properly set method and callback', (done: DoneFn) => {client.jsonp('/test', 'myCallback').subscribe(() => done());backend.expectOne({method: 'JSONP', url: '/test?myCallback=JSONP_CALLBACK'}).flush('hello world');});
});

Angular4 Angular HttpClient相关推荐

  1. angular HttpClient post put patch del 方法(2)-Promise 服务

    之前做了在一个页面的CRUD的方法,现实中webapi模块往往是单独写服务的,所以修改了一下原来的设计和结构,还是需要很多知识的. 2017.11.15增加patch方法 ,改进服务程序优化写法 20 ...

  2. angular HttpClient 配置

    angular的资料很少,并且坑很多,报错也不是很好解决,研究这个花了好几天时间. 首先,先查看自己的anuglar版本是不是4.3.0以上,HttpClient是anuglar4.3中新加入的特性, ...

  3. Angular HTTPClient的使用方法

    这个例子演示了如何使用Angular的HttpClientModule. 在app.module.ts里导入HttpClientModule: import { HttpClientModule } ...

  4. Angular HttpClient responseType和observe的坑人行为

    现在是凌晨2点半. 我从晚上8点就遇到这个问题了,一直想不通,直到刚才查到https://github.com/angular/angular/issues/18586才发现被坑了一回. 问题是这样的 ...

  5. Angular HttpClient.get的实现单步调试

    进入get方法: request方法实现的源代码: @Injectable() export class HttpClient {constructor(private handler: HttpHa ...

  6. angular4 使用HttpClient拦截器 检查token失效,返回登录页面

    1.首先创建一个拦截器服务:InterceptorService.ts 2.在app.module.ts文件里引入拦截器 import {InterceptorService} from './Int ...

  7. 解决Angular HttpClient设置headers后,Body体格式问题

    Angular headers默认的Content-Type为 multipart/form-data; boundary=----WebKitFormBoundaryTyqm71FGjlNaJxbE ...

  8. angular HttpClient getbyid 方法获取数据

    简单传参的方法,最常用的是getbyid 方法. 直接上代码: getbyId(id: string) {this.myhttp.get('http://192.168.2.139:9002/api/ ...

  9. angular 模块构建_如何通过11个简单的步骤从头开始构建Angular 8应用

    angular 模块构建 Angular is one of the three most popular frameworks for front-end development, alongsid ...

最新文章

  1. 微信小程序与uniapp中 px与rpx 相互转换
  2. Pyomo+GLPK使用
  3. golang中的权限
  4. 【算法与数据结构】在n个数中取第k大的数(基础篇)
  5. 数据采集之用户区域(USER)事件
  6. [Elasticsearch2.x] 多字段搜索 (三) - multi_match查询和多数字段 译
  7. VS 添加文件添加文件成链接
  8. 扩展类加载器 Extension ClassLoader
  9. c语言调用createthread线程的头文件_易语言API多线程总汇
  10. FCKeditor配置和使用(转)
  11. PDF手型工具 有一个小箭头
  12. 学校计算机联想硬盘保护系统管理员密码,联想硬盘保护系统管理员密码是多少...
  13. 恶意软件、反病毒网关简析
  14. Sublime Text 3 安装控件中心时报错Error validating download (got 6f4c264a24d933ce70df5dedc)
  15. 【JZOJ 3397】雨天的尾巴
  16. JavaScript异步与同步解析
  17. EXCEL中阿拉伯数字版转成汉语大写代码
  18. Hibernate 查询方式(HQL/QBC/QBE)汇总
  19. 超级狗无法识别到开发狗
  20. Arcgis实例操作8---地形高程分析、提取该DEM数据的水文坡长、提取山顶点数据

热门文章

  1. 计算机学硕一志愿仅录取一人,调剂录取几十人!重庆理工大学人工智能学院...
  2. mysql 幻读的隔离_MySQL的RR隔离级别与幻读问题
  3. C语言实现存款利息计算
  4. MALTAB之stem函数
  5. Excel文件转换为txt文本第一次更新
  6. Java:文件写入读取操作和工具类
  7. SD-WAN,让你的组网更灵活
  8. Lichee(二) 在sun4i_crane平台下的编译
  9. 反射模式python
  10. 垃圾渗滤液的形成过程!