Angular的HttpClient介绍
Angular 4.3 为我们 带来了一种使用 HttpClient 库处理 http 请求的更简单的新方法。 它以新名称提供,以避免对当前 Http 库造成重大更改。 HttpClient 还为我们提供了高级功能,例如侦听进度事件和拦截器以监视或修改请求或响应的能力。
确保您使用 Angular 4.3 或更高版本来试用 HttpClient
安装
首先,您需要在应用模块中从 @angular/common/http 导入 HttpClientModule:
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
然后你可以像往常一样使用 HttpClient :
一些.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class DataService {
constructor(private http: HttpClient) {}
基本用法
发出基本的 GET、POST、PUT、PATCH 或 DELETE 请求与您过去使用的旧 Http API 非常相似。 一个主要区别是默认情况下需要 JSON 响应,因此不再需要显式解析 JSON 响应。
这是一个示例 GET 请求:
// ...
constructor(private http: HttpClient) {}
getData() {
this.http.get(this.url).subscribe(res => {
this.posts = res;
});
}
如果您期望 JSON 以外的其他内容作为响应,您可以使用带有 responseType 键的对象指定期望的响应类型:
getData() {
this.http.get(this.url, { responseType: 'text' }).subscribe(res => {
this.data = res;
});
}
您还可以为响应的形状定义一个接口,并针对该接口进行类型检查:
interface Post {
title: string;
body: string;
};
// ...
constructor(private http: HttpClient) {}
getData() {
this.http.get<Post>(this.url).subscribe(res => {
this.postTitle = res.title;
});
}
默认情况下,HttpClient 返回响应的正文。 您可以通过将 observe 键设置为 'response' 的值来传入对象以获得完整响应。 这对于检查某些标题很有用:
getData() {
this.http.get<Post>(this.url, { observe: 'response' }).subscribe(res => {
this.powered = res.headers.get('X-Powered-By');
this.postTitle = res.body.title;
});
}
发布、放置和修补请求
发出 POST、PUT 或 PATCH 请求同样简单:
postData() {
this.http.post(this.url, this.payload).subscribe();
}
请注意我们仍然必须订阅才能发出请求。 没有订阅调用,请求是冷的。 您显然可能想要处理任何回复或错误:
postData() {
this.http.post(this.url, this.payload).subscribe(
res => {
console.log(res);
},
(err: HttpErrorResponse) => {
console.log(err.error);
console.log(err.name);
console.log(err.message);
console.log(err.status);
}
);
}
请求错误的类型为 HttpErrorResponse,其中包含错误名称、错误消息和服务器状态等。
也可以使用作为第三个参数传入的对象中的 headers 或 params 键将传入标头或查询参数的选项添加到 POST、PUT 或 PATCH 请求:
updatePost() {
this.http
.put(this.url, this.payload, {
params: new HttpParams().set('id', '56784'),
headers: new HttpHeaders().set('Authorization', 'some-token')
})
.subscribe(...);
}
注意这里使用了 HttpParams 和 HttpHeaders 类。 您还需要从 @angular/common/http 导入这些。
进度事件
HttpClient 的一个很棒的新功能是能够监听进度事件。 这可以在任何类型的请求上完成,并且在请求事件的生命周期中将提供不同的信息。 这是一个 GET 请求的完整示例:
import { Injectable } from '@angular/core';
import {
HttpClient,
HttpRequest,
HttpEvent,
HttpEventType
} from '@angular/common/http';
@Injectable()
export class DataService {
url = '/some/api';
constructor(private http: HttpClient) {}
getData() {
const req = new HttpRequest('GET', this.url, {
reportProgress: true
});
this.http.request(req).subscribe((event: HttpEvent<any>) => {
switch (event.type) {
case HttpEventType.Sent:
console.log('Request sent!');
break;
case HttpEventType.ResponseHeader:
console.log('Response header received!');
break;
case HttpEventType.DownloadProgress:
const kbLoaded = Math.round(event.loaded / 1024);
console.log(`Download in progress! ${ kbLoaded }Kb loaded`);
break;
case HttpEventType.Response:
console.log('😺 Done!', event.body);
}
});
}
}
- 我们首先需要通过创建 HttpRequest 类的实例并使用 reportProgress 选项来构建请求对象。
- 然后我们订阅我们的请求对象以发起请求并在请求的生命周期内监听不同的事件类型。 我们可以根据事件类型做出适当的反应。 可用的事件类型有 Sent、UploadProgress、ResponseHeader、DownloadProgress、Response 和 User[ X152X]。
- 在上面的例子中,我们从 GET 响应中获取了到目前为止下载的数据量,在 POST 或 PUT 请求的情况下,我们还可以使用 [X230X ]。 这使得向用户显示进度条变得非常容易。
🤓 这篇文章介绍了 HttpClient 的基础知识,接下来将解决 HttpClient 的杀手级特性 interceptors 的使用。 您也可以前往 官方文档 进行更深入的了解。