HttpClient
大多数前端应用都需要通过 HTTP 协议与后端服务器通讯。现代浏览器支持使用两种不同的 API 发起 HTTP 请求:XMLHttpRequest
接口和 fetch()
API。
@angular/common/http
中的 HttpClient
类为 Angular 应用程序提供了一个简化的 API 来实现 HTTP 客户端功能。它基于浏览器提供的 XMLHttpRequest
接口。 HttpClient
带来的其它优点包括:可测试性、强类型的请求和响应对象、发起请求与接收响应时的拦截器支持,以及更好的、基于可观察(Observable)对象的 API 以及流式错误处理机制。
该应用代码并不需要数据服务器。 它基于 Angular in-memory-web-api 库,该库会替换 HttpClient
模块中的 HttpBackend
。用于替换的这个服务会模拟 REST 风格的后端的行为。
到 AppModule
的 imports
中查看这个库是如何配置的。
准备工作
要想使用 HttpClient
,就要先导入 Angular 的 HttpClientModule
。大多数应用都会在根模块 AppModule
中导入它。
app/app.module.ts (excerpt)
content_copyimport { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
// import HttpClientModule after BrowserModule.
HttpClientModule,
],
declarations: [
AppComponent,
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
在 AppModule
中导入 HttpClientModule
之后,你可以把 HttpClient
注入到应用类中,就像下面的 ConfigService
例子中这样。
app/config/config.service.ts (excerpt)
content_copyimport { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class ConfigService {
constructor(private http: HttpClient) { }
}
获取 JSON 数据
应用通常会从服务器上获取 JSON 数据。 比如,该应用可能要从服务器上获取配置文件 config.json
,其中指定了一些特定资源的 URL。
assets/config.json
content_copy{
"heroesUrl": "api/heroes",
"textfile": "assets/textfile.txt"
}
ConfigService
会通过 HttpClient
的 get()
方法取得这个文件。
app/config/config.service.ts (getConfig v.1)
content_copyconfigUrl = 'assets/config.json';
getConfig() {
return this.http.get(this.configUrl);
}
像 ConfigComponent
这样的组件会注入 ConfigService
,并调用其 getConfig
方法。
app/config/config.component.ts (showConfig v.1)
content_copyshowConfig() {
this.configService.getConfig()
.subscribe((data: Config) => this.config = {
heroesUrl: data['heroesUrl'],
textfile: data['textfile']
});
}
这个服务方法返回配置数据的 Observable
对象,所以组件要订阅(subscribe) 该方法的返回值。 订阅时的回调函数会把这些数据字段复制到组件的 config
对象中,它会在组件的模板中绑定,以供显示。
为什么要写服务
这个例子太简单,所以它也可以在组件本身的代码中调用 Http.get()
,而不用借助服务。
不过,数据访问很少能一直这么简单。 你通常要对数据做后处理、添加错误处理器,还可能加一些重试逻辑,以便应对网络抽风的情况。
该组件很快就会因为这些数据方式的细节而变得杂乱不堪。 组件变得难以理解、难以测试,并且这些数据访问逻辑无法被复用,也无法标准化。
这就是为什么最佳实践中要求把数据展现逻辑从数据访问逻辑中拆分出去,也就是说把数据访问逻辑包装进一个单独的服务中, 并且在组件中把数据访问逻辑委托给这个服务。就算是这么简单的应用也要如此。
带类型检查的响应
该订阅的回调需要用通过括号中的语句来提取数据的值。
content_copy.subscribe((data: Config) => this.config = {
heroesUrl: data['heroesUrl'],
textfile: data['textfile']
});
你没法写成 data.heroesUrl
,因为 TypeScript 会报告说来自服务器的 data
对象中没有名叫 heroesUrl
的属性。
这是因为 HttpClient.get()
方法把 JSON 响应体解析成了匿名的 Object
类型。它不知道该对象的具体形态如何。
你可以告诉 HttpClient
该响应体的类型,以便让对这种输出的消费更容易、更明确。
首先,定义一个具有正确形态的接口:
content_copyexport interface Config {
heroesUrl: string;
textfile: string;
}
然后,在服务器中把该接口指定为 HttpClient.get()
调用的类型参数。
app/config/config.service.ts (getConfig v.2)
content_copygetConfig() {
// now returns an Observable of Config
return this.http.get<Config>(this.configUrl);
}
修改后的组件方法,其回调函数中获取一个带类型的对象,它易于使用,且消费起来更安全:
app/config/config.component.ts (showConfig v.2)
content_copyconfig: Config;
showConfig() {
this.configService.getConfig()
// clone the data object, using its known Config shape
.subscribe((data: Config) => this.config = { ...data });
}
读取完整的响应体
响应体可能并不包含你需要的全部信息。有时候服务器会返回一个特殊的响应头或状态码,以标记出特定的条件,因此读取它们可能是必要的。
要这样做,你就要通过 observe
选项来告诉 HttpClient
,你想要完整的响应信息,而不是只有响应体:
content_copygetConfigResponse(): Observable<HttpResponse<Config>> {
return this.http.get<Config>(
this.configUrl, { observe: 'response' });
}
现在 HttpClient.get()
会返回一个 HttpResponse
类型的 Observable
,而不只是 JSON 数据。
该组件的 showConfigResponse()
方法会像显示配置数据一样显示响应头:
app/config/config.component.ts (showConfigResponse)
content_copyshowConfigResponse() {
this.configService.getConfigResponse()
// resp is of type `HttpResponse<Config>`
.subscribe(resp => {
// display its headers
const keys = resp.headers.keys();
this.headers = keys.map(key =>
`${key}: ${resp.headers.get(key)}`);
// access the body directly, which is typed as `Config`.
this.config = { ... resp.body };
});
}
如你所见,该响应对象具有一个带有正确类型的 body
属性。
错误处理
如果这个请求导致了服务器错误怎么办?甚至,在烂网络下请求都没到服务器该怎么办?HttpClient
就会返回一个错误(error)而不再是成功的响应。
通过在 .subscribe()
中添加第二个回调函数,你可以在组件中处理它:
app/config/config.component.ts (showConfig v.3 with error handling)
content_copyshowConfig() {
this.configService.getConfig()
.subscribe(
(data: Config) => this.config = { ...data }, // success path
error => this.error = error // error path
);
}
在数据访问失败时给用户一些反馈,确实是个好主意。 不过,直接显示由 HttpClient
返回的原始错误数据还远远不够。
获取错误详情
检测错误的发生是第一步,不过如果知道具体发生了什么错误才会更有用。上面例子中传给回调函数的 err
参数的类型是 HttpErrorResponse
,它包含了这个错误中一些很有用的信息。
可能发生的错误分为两种。如果后端返回了一个失败的返回码(如 404、500 等),它会返回一个错误响应体。
或者,如果在客户端这边出了错误(比如在 RxJS 操作符 (operator) 中抛出的异常或某些阻碍完成这个请求的网络错误),就会抛出一个 Error
类型的异常。
HttpClient
会在 HttpErrorResponse
中捕获所有类型的错误信息,你可以查看这个响应体以了解到底发生了什么。
错误的探查、解释和解决是你应该在服务中做的事情,而不是在组件中。
你可能首先要设计一个错误处理器,就像这样:
app/config/config.service.ts (handleError)
content_copyprivate handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
'Something bad happened; please try again later.');
};
注意,该处理器返回一个带有用户友好的错误信息的 RxJS ErrorObservable
对象。 该服务的消费者期望服务的方法返回某种形式的 Observable
,就算是“错误的”也可以。
现在,你获取了由 HttpClient
方法返回的 Observable
,并把它们通过管道传给错误处理器。
app/config/config.service.ts (getConfig v.3 with error handler)
content_copygetConfig() {
return this.http.get<Config>(this.configUrl)
.pipe(
catchError(this.handleError)
);
}
retry()
有时候,错误只是临时性的,只要重试就可能会自动消失。 比如,在移动端场景中可能会遇到网络中断的情况,只要重试一下就能拿到正确的结果。
RxJS 库提供了几个 retry
操作符,它们值得仔细看看。 其中最简单的是 retry()
,它可以对失败的 Observable
自动重新订阅几次。对 HttpClient
方法调用的结果进行重新订阅会导致重新发起 HTTP 请求。
把它插入到 HttpClient
方法结果的管道中,就放在错误处理器的紧前面。
app/config/config.service.ts (getConfig with retry)
content_copygetConfig() {
return this.http.get<Config>(this.configUrl)
.pipe(
retry(3), // retry a failed request up to 3 times
catchError(this.handleError) // then handle the error
);
}
可观察对象 (Observable) 与操作符 (operator)
本章的前一节中引用了 RxJS 的 Observable
和 operator
,比如 catchError
和 retry
。 接下来你还会遇到更多 RxJS 中的概念。
RxJS 是一个库,用于把异步调用和基于回调的代码组合成函数式(functional)的、响应式(reactive)的风格。 很多 Angular API,包括 HttpClient
都会生成和消费 RxJS 的 Observable
。
RxJS 本身超出了本章的范围。你可以在网络上找到更多的学习资源。 虽然只用少量的 RxJS 知识就可以获得解决方案,不过以后你会逐步提高 RxJS 技能,以便更高效的使用 HttpClient
。
如果你在跟着教程敲下面这些代码片段,要注意你要自己导入这里出现的 RxJS 的可观察对象和操作符。就像 ConfigService
中的这些导入。
app/config/config.service.ts (RxJS imports)
content_copyimport { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
请求非 JSON 格式的数据
不是所有的 API 都会返回 JSON 数据。在下面这个例子中,DownloaderService
中的方法会从服务器读取文本文件, 并把文件的内容记录下来,然后把这些内容使用 Observable<string>
的形式返回给调用者。
app/downloader/downloader.service.ts (getTextFile)
content_copygetTextFile(filename: string) {
// The Observable returned by get() is of type Observable<string>
// because a text response was specified.
// There's no need to pass a <string> type parameter to get().
return this.http.get(filename, {responseType: 'text'})
.pipe(
tap( // Log the result or error
data => this.log(filename, data),
error => this.logError(filename, error)
)
);
}
这里的 HttpClient.get()
返回字符串而不是默认的 JSON 对象,因为它的 responseType
选项是 'text'
。
RxJS 的 tap
操作符(可看做 wiretap - 窃听),让这段代码探查由可观察对象传过来的正确值和错误值,而不用打扰它们。
在 DownloaderComponent
中的 download()
方法通过订阅这个服务中的方法来发起一次请求。
app/downloader/downloader.component.ts (download)
content_copydownload() {
this.downloaderService.getTextFile('assets/textfile.txt')
.subscribe(results => this.contents = results);
}
把数据发送到服务器
除了从服务器获取数据之外,HttpClient
还支持修改型的请求,也就是说,通过 PUT
、POST
、DELETE
这样的 HTTP 方法把数据发送到服务器。
本指南中的这个范例应用包括一个简化版本的《英雄指南》,它会获取英雄数据,并允许用户添加、删除和修改它们。
下面的这些章节中包括该范例的 HeroesService
中的一些方法片段。
添加请求头
很多服务器在进行保存型操作时需要额外的请求头。 比如,它们可能需要一个 Content-Type
头来显式定义请求体的 MIME 类型。 也可能服务器会需要一个认证用的令牌(token)。
HeroesService
在 httpOptions
对象中就定义了一些这样的请求头,并把它传给每个 HttpClient
的保存型方法。
app/heroes/heroes.service.ts (httpOptions)
content_copyimport { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
};
发起一个 POST 请求
应用经常把数据 POST
到服务器。它们会在提交表单时进行 POST
。 下面这个例子中,HeroesService
在把英雄添加到数据库中时,就会使用 POST
。
app/heroes/heroes.service.ts (addHero)
content_copy/** POST: add a new hero to the database */
addHero (hero: Hero): Observable<Hero> {
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
.pipe(
catchError(this.handleError('addHero', hero))
);
}
HttpClient.post()
方法像 get()
一样也有类型参数(你会希望服务器返回一个新的英雄对象),它包含一个资源 URL。
它还接受另外两个参数:
hero
- 要POST
的请求体数据。httpOptions
- 这个例子中,该方法的选项指定了所需的请求头。
当然,它捕获错误的方式很像前面描述的操作方式。
HeroesComponent
通过订阅该服务方法返回的 Observable
发起了一次实际的 POST
操作。
app/heroes/heroes.component.ts (addHero)
content_copythis.heroesService.addHero(newHero)
.subscribe(hero => this.heroes.push(hero));
当服务器成功做出响应时,会带有这个新创建的英雄,然后该组件就会把这个英雄添加到正在显示的 heroes
列表中。
发起 DELETE
请求
该应用可以把英雄的 id 传给 HttpClient.delete
方法的请求 URL 来删除一个英雄。
app/heroes/heroes.service.ts (deleteHero)
content_copy/** DELETE: delete the hero from the server */
deleteHero (id: number): Observable<{}> {
const url = `${this.heroesUrl}/${id}`; // DELETE api/heroes/42
return this.http.delete(url, httpOptions)
.pipe(
catchError(this.handleError('deleteHero'))
);
}
当 HeroesComponent
订阅了该服务方法返回的 Observable
时,就会发起一次实际的 DELETE
操作。
app/heroes/heroes.component.ts (deleteHero)
content_copythis.heroesService.deleteHero(hero.id).subscribe();
该组件不会等待删除操作的结果,所以它的 subscribe (订阅)中没有回调函数。不过就算你不关心结果,也仍然要订阅它。调用 subscribe()
方法会执行这个可观察对象,这时才会真的发起 DELETE 请求。
你必须调用 subscribe()
,否则什么都不会发生。仅仅调用 HeroesService.deleteHero()
是不会发起 DELETE 请求的。
content_copy// oops ... subscribe() is missing so nothing happens
this.heroesService.deleteHero(hero.id);
别忘了订阅!
在调用方法返回的可观察对象的 subscribe()
方法之前,HttpClient
方法不会发起 HTTP 请求。这适用于 HttpClient
的所有方法。
AsyncPipe
会自动为你订阅(以及取消订阅)。
HttpClient
的所有方法返回的可观察对象都设计为冷的。 HTTP 请求的执行都是延期执行的,让你可以用 tap
和 catchError
这样的操作符来在实际执行什么之前,先对这个可观察对象进行扩展。
调用 subscribe(...)
会触发这个可观察对象的执行,并导致 HttpClient
组合并把 HTTP 请求发给服务器。
你可以把这些可观察对象看做实际 HTTP 请求的蓝图。
实际上,每个 subscribe()
都会初始化此可观察对象的一次单独的、独立的执行。 订阅两次就会导致发起两个 HTTP 请求。
content_copyconst req = http.get<Heroes>('/api/heroes');
// 0 requests made - .subscribe() not called.
req.subscribe();
// 1 request made.
req.subscribe();
// 2 requests made.
发起 PUT 请求
应用可以发送 PUT 请求,来使用修改后的数据完全替换掉一个资源。 下面的 HeroesService
例子和 POST 的例子很像。
app/heroes/heroes.service.ts (updateHero)
content_copy/** PUT: update the hero on the server. Returns the updated hero upon success. */
updateHero (hero: Hero): Observable<Hero> {
return this.http.put<Hero>(this.heroesUrl, hero, httpOptions)
.pipe(
catchError(this.handleError('updateHero', hero))
);
}
因为前面解释过的原因,调用者(这里是 HeroesComponent.update()
)必须 subscribe()
由 HttpClient.put()
返回的可观察对象,以发起这个调用。
高级用法
我们已经讨论了 @angular/common/http
的基本 HTTP 功能,但有时候除了单纯发起请求和取回数据之外,你还要再做点别的。
配置请求
待发送请求的其它方面可以通过传给 HttpClient
方法最后一个参数中的配置对象进行配置。
以前你曾在 HeroesService
中通过在其保存方法中传入配置对象 httpOptions
设置过默认头。 你还可以做更多。
修改这些头
你没法直接修改前述配置对象中的现有头,因为这个 HttpHeaders
类的实例是不可变的。
改用 set()
方法代替。 它会返回当前实例的一份克隆,其中应用了这些新修改。
比如在发起下一个请求之前,如果旧的令牌已经过期了,你可能还要修改认证头。
content_copyhttpOptions.headers =
httpOptions.headers.set('Authorization', 'my-new-auth-token');
URL 参数
添加 URL 搜索参数也与此类似。 这里的 searchHeroes
方法会查询名字中包含搜索词的英雄列表。
content_copy/* GET heroes whose name contains search term */
searchHeroes(term: string): Observable<Hero[]> {
term = term.trim();
// Add safe, URL encoded search parameter if there is a search term
const options = term ?
{ params: new HttpParams().set('name', term) } : {};
return this.http.get<Hero[]>(this.heroesUrl, options)
.pipe(
catchError(this.handleError<Hero[]>('searchHeroes', []))
);
}
如果有搜索词,这段代码就会构造一个包含进行过 URL 编码的搜索词的选项对象。如果这个搜索词是“foo”,这个 GET 请求的 URL 就会是 api/heroes/?name=foo
。
HttpParams
是不可变的,所以你也要使用 set()
方法来修改这些选项。
请求的防抖(debounce)
这个例子还包含了搜索 npm 包的特性。
当用户在搜索框中输入名字时,PackageSearchComponent
就会把一个根据名字搜索包的请求发送给 NPM 的 web api。
下面是模板中的相关代码片段:
app/package-search/package-search.component.html (search)
content_copy<input (keyup)="search($event.target.value)" id="name" placeholder="Search"/>
<ul>
<li *ngFor="let package of packages$ | async">
<b>{{package.name}} v.{{package.version}}</b> -
<i>{{package.description}}</i>
</li>
</ul>
(keyup)
事件绑定把每次击键都发送给了组件的 search
()
方法。
如果每次击键都发送一次请求就太昂贵了。 最好能等到用户停止输入时才发送请求。 使用 RxJS 的操作符就能轻易实现它,参见下面的代码片段:
app/package-search/package-search.component.ts (excerpt))
content_copywithRefresh = false;packages$: Observable<NpmPackageInfo[]>;private searchText$ = new Subject<string>(); search(packageName: string) { this.searchText$.next(packageName);} ngOnInit() { this.packages$ = this.searchText$.pipe( debounceTime(500), distinctUntilChanged(), switchMap(packageName => this.searchService.search(packageName, this.withRefresh)) );} constructor(private searchService: PackageSearchService) { }
searchText$
是一个序列,包含用户输入到搜索框中的所有值。 它定义成了 RxJS 的 Subject
对象,这表示它是一个多播 Observable
,同时还可以自行调用 next(value)
来产生值。 search
()
方法中就是这么做的。
除了把每个 searchText
的值都直接转发给 PackageSearchService
之外,ngOnInit()
中的代码还通过下列三个操作符对这些搜索值进行管道处理:
debounceTime(500)
- 等待,直到用户停止输入(这个例子中是停止 1/2 秒)。distinctUntilChanged()
- 等待,直到搜索内容发生了变化。switchMap()
- 把搜索请求发送给服务。
这些代码把 packages$
设置成了使用搜索结果组合出的 Observable
对象。 模板中使用 AsyncPipe 订阅了 packages$
,一旦搜索结果的值发回来了,就显示这些搜索结果。
这样,只有当用户停止了输入且搜索值和以前不一样的时候,搜索值才会传给服务。
稍后 解释了这个 withRefresh
选项。
switchMap()
这个 switchMap()
操作符有三个重要的特征:
- 它的参数是一个返回
Observable
的函数。PackageSearchService.search
会返回Observable
,其它数据服务也一样。 - 如果以前的搜索结果仍然是在途状态(这会出现在慢速网络中),它会取消那个请求,并发起这个新的搜索。
- 它会按照原始的请求顺序返回这些服务的响应,而不用关心服务器实际上是以乱序返回的它们。
如果你觉得将来会复用这些防抖逻辑, 可以把它移到单独的工具函数中,或者移到 PackageSearchService
中。
拦截请求和响应
HTTP 拦截机制是 @angular/common/http
中的主要特性之一。 使用这种拦截机制,你可以声明一些拦截器,用它们监视和转换从应用发送到服务器的 HTTP 请求。 拦截器还可以用监视和转换从服务器返回到本应用的那些响应。 多个选择器会构成一个“请求/响应处理器”的双向链表。
拦截器可以用一种常规的、标准的方式对每一次 HTTP 的请求/响应任务执行从认证到记日志等很多种隐式任务。
如果没有拦截机制,那么开发人员将不得不对每次 HttpClient
调用显式实现这些任务。
编写拦截器
要实现拦截器,就要实现一个实现了 HttpInterceptor
接口中的 intercept()
方法的类。
这里是一个什么也不做的空白拦截器,它只会不做任何修改的传递这个请求。
app/http-interceptors/noop-interceptor.ts
content_copyimport { Injectable } from '@angular/core';
import {
HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from '@angular/common/http';
import { Observable } from 'rxjs';
/** Pass untouched request through to the next request handler. */
@Injectable()
export class NoopInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
return next.handle(req);
}
}
intercept
方法会把请求转换成一个最终返回 HTTP 响应体的 Observable
。 在这个场景中,每个拦截器都完全能自己处理这个请求。
大多数拦截器拦截都会在传入时检查请求,然后把(可能被修改过的)请求转发给 next
对象的 handle()
方法,而 next
对象实现了 HttpHandler
接口。
content_copyexport abstract class HttpHandler {
abstract handle(req: HttpRequest<any>): Observable<HttpEvent<any>>;
}
像 intercept()
一样,handle()
方法也会把 HTTP 请求转换成 HttpEvents
组成的 Observable
,它最终包含的是来自服务器的响应。intercept()
函数可以检查这个可观察对象,并在把它返回给调用者之前修改它。
这个无操作的拦截器,会直接使用原始的请求调用 next.handle()
,并返回它返回的可观察对象,而不做任何后续处理。
next
对象
next
对象表示拦截器链表中的下一个拦截器。 这个链表中的最后一个 next
对象就是 HttpClient
的后端处理器(backend handler),它会把请求发给服务器,并接收服务器的响应。
大多数的拦截器都会调用 next.handle()
,以便这个请求流能走到下一个拦截器,并最终传给后端处理器。 拦截器也可以不调用 next.handle()
,使这个链路短路,并返回一个带有人工构造出来的服务器响应的 自己的 Observable
。
这是一种常见的中间件模式,在像 Express.js 这样的框架中也会找到它。
提供这个拦截器
这个 NoopInterceptor
就是一个由 Angular 依赖注入 (DI)系统管理的服务。 像其它服务一样,你也必须先提供这个拦截器类,应用才能使用它。
由于拦截器是 HttpClient
服务的(可选)依赖,所以你必须在提供 HttpClient
的同一个(或其各级父注入器)注入器中提供这些拦截器。 那些在 DI 创建完 HttpClient
之后再提供的拦截器将会被忽略。
由于在 AppModule
中导入了 HttpClientModule
,导致本应用在其根注入器中提供了 HttpClient
。所以你也同样要在 AppModule
中提供这些拦截器。
在从 @angular/common/http
中导入了 HTTP_INTERCEPTORS
注入令牌之后,编写如下的 NoopInterceptor
提供商注册语句:
content_copy{ provide: HTTP_INTERCEPTORS, useClass: NoopInterceptor, multi: true },
注意 multi: true
选项。 这个必须的选项会告诉 Angular HTTP_INTERCEPTORS
是一个多重提供商的令牌,表示它会注入一个多值的数组,而不是单一的值。
你也可以直接把这个提供商添加到 AppModule
中的提供商数组中,不过那样会非常啰嗦。况且,你将来还会用这种方式创建更多的拦截器并提供它们。 你还要特别注意提供这些拦截器的顺序。
认真考虑创建一个封装桶(barrel)文件,用于把所有拦截器都收集起来,一起提供给 httpInterceptorProviders
数组,可以先从这个 NoopInterceptor
开始。
app/http-interceptors/index.ts
content_copy/* "Barrel" of Http Interceptors */
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { NoopInterceptor } from './noop-interceptor';
/** Http interceptor providers in outside-in order */
export const httpInterceptorProviders = [
{ provide: HTTP_INTERCEPTORS, useClass: NoopInterceptor, multi: true },
];
然后导入它,并把它加到 AppModule
的 providers
数组中,就像这样:
app/app.module.ts (interceptor providers)
content_copyproviders: [
httpInterceptorProviders
],
当你再创建新的拦截器时,就同样把它们添加到 httpInterceptorProviders
数组中,而不用再修改 AppModule
。
在完整版的范例代码中还有更多的拦截器。
拦截器的顺序
Angular 会按照你提供它们的顺序应用这些拦截器。 如果你提供拦截器的顺序是先 A,再 B,再 C,那么请求阶段的执行顺序就是 A->B->C,而响应阶段的执行顺序则是 C->B->A。
以后你就再也不能修改这些顺序或移除某些拦截器了。 如果你需要动态启用或禁用某个拦截器,那就要在那个拦截器中自行实现这个功能。
HttpEvents
你可能会期望 intercept()
和 handle()
方法会像大多数 HttpClient
中的方法那样返回 HttpResponse
<any>
的可观察对象。
然而并没有,它们返回的是 HttpEvent
<any>
的可观察对象。
这是因为拦截器工作的层级比那些 HttpClient
方法更低一些。每个 HTTP 请求都可能会生成很多个事件,包括上传和下载的进度事件。 实际上,HttpResponse
类本身就是一个事件,它的类型(type
)是 HttpEventType.HttpResponseEvent
。
很多拦截器只关心发出的请求,而对 next.handle()
返回的事件流不会做任何修改。
但那些要检查和修改来自 next.handle()
的响应体的拦截器希望看到所有这些事件。 所以,你的拦截器应该返回你没碰过的所有事件,除非你有充分的理由不这么做。
不可变性
虽然拦截器有能力改变请求和响应,但 HttpRequest
和 HttpResponse
实例的属性却是只读(readonly
)的, 因此,它们在很大意义上说是不可变对象。
有充足的理由把它们做成不可变对象:应用可能会重试发送很多次请求之后才能成功,这就意味着这个拦截器链表可能会多次重复处理同一个请求。 如果拦截器可以修改原始的请求对象,那么重试阶段的操作就会从修改过的请求开始,而不是原始请求。 而这种不可变性,可以确保这些拦截器在每次重试时看到的都是同样的原始请求。
通过把 HttpRequest
的属性设置为只读的,TypeScript 可以防止你犯这种错误。
content_copy// Typescript disallows the following assignment because req.url is readonly
req.url = req.url.replace('http://', 'https://');
要想修改该请求,就要先克隆它,并修改这个克隆体,然后再把这个克隆体传给 next.handle()
。 你可以用一步操作中完成对请求的克隆和修改,例子如下:
app/http-interceptors/ensure-https-interceptor.ts (excerpt)
content_copy// clone request and replace 'http://' with 'https://' at the same time
const secureReq = req.clone({
url: req.url.replace('http://', 'https://')
});
// send the cloned, "secure" request to the next handler.
return next.handle(secureReq);
这个 clone()
方法的哈希型参数允许你在复制出克隆体的同时改变该请求的某些特定属性。
请求体
readonly
这种赋值保护,无法防范深修改(修改子对象的属性),也不能防范你修改请求体对象中的属性。
content_copyreq.body.name = req.body.name.trim(); // bad idea!
如果你必须修改请求体,那么就要先复制它,然后修改这个复本,clone()
这个请求,然后把这个请求体的复本作为新的请求体,例子如下:
app/http-interceptors/trim-name-interceptor.ts (excerpt)
content_copy// copy the body and trim whitespace from the name property
const newBody = { ...body, name: body.name.trim() };
// clone request and set its body
const newReq = req.clone({ body: newBody });
// send the cloned request to the next handler.
return next.handle(newReq);
清空请求体
Clearing the request body
有时你需要清空请求体,而不是替换它。 如果你把克隆后的请求体设置成 undefined
,Angular 会认为你是想让这个请求体保持原样。 这显然不是你想要的。 但如果把克隆后的请求体设置成 null
,那 Angular 就知道你是想清空这个请求体了。
content_copynewReq = req.clone({ ... }); // body not mentioned => preserve original body
newReq = req.clone({ body: undefined }); // preserve original body
newReq = req.clone({ body: null }); // clear the body
设置默认请求头
应用通常会使用拦截器来设置外发请求的默认请求头。
该范例应用具有一个 AuthService
,它会生成一个认证令牌。 在这里,AuthInterceptor
会注入该服务以获取令牌,并对每一个外发的请求添加一个带有该令牌的认证头:
app/http-interceptors/auth-interceptor.ts
content_copyimport { AuthService } from '../auth.service'; @Injectable()export class AuthInterceptor implements HttpInterceptor { constructor(private auth: AuthService) {} intercept(req: HttpRequest<any>, next: HttpHandler) { // Get the auth token from the service. const authToken = this.auth.getAuthorizationToken(); // Clone the request and replace the original headers with // cloned headers, updated with the authorization. const authReq = req.clone({ headers: req.headers.set('Authorization', authToken) }); // send cloned request with header to the next handler. return next.handle(authReq); }}
这种在克隆请求的同时设置新请求头的操作太常见了,因此它还有一个快捷方式 setHeaders
:
content_copy// Clone the request and set the new header in one step.
const authReq = req.clone({ setHeaders: { Authorization: authToken } });
这种可以修改头的拦截器可以用于很多不同的操作,比如:
- 认证 / 授权
- 控制缓存行为。比如
If-Modified-Since
- XSRF 防护
记日志
因为拦截器可以同时处理请求和响应,所以它们也可以对整个 HTTP 操作进行计时和记录日志。
考虑下面这个 LoggingInterceptor
,它捕获请求的发起时间、响应的接收时间,并使用注入的 MessageService
来发送总共花费的时间。
app/http-interceptors/logging-interceptor.ts)
content_copyimport { finalize, tap } from 'rxjs/operators';import { MessageService } from '../message.service'; @Injectable()export class LoggingInterceptor implements HttpInterceptor { constructor(private messenger: MessageService) {} intercept(req: HttpRequest<any>, next: HttpHandler) { const started = Date.now(); let ok: string; // extend server response observable with logging return next.handle(req) .pipe( tap( // Succeeds when there is a response; ignore other events event => ok = event instanceof HttpResponse ? 'succeeded' : '', // Operation failed; error is an HttpErrorResponse error => ok = 'failed' ), // Log when response observable either completes or errors finalize(() => { const elapsed = Date.now() - started; const msg = `${req.method} "${req.urlWithParams}" ${ok} in ${elapsed} ms.`; this.messenger.add(msg); }) ); }}
RxJS 的 tap
操作符会捕获请求成功了还是失败了。 RxJS 的 finalize
操作符无论在响应成功还是失败时都会调用(这是必须的),然后把结果汇报给 MessageService
。
在这个可观察对象的流中,无论是 tap
还是 finalize
接触过的值,都会照常发送给调用者。
缓存
拦截器还可以自行处理这些请求,而不用转发给 next.handle()
。
比如,你可能会想缓存某些请求和响应,以便提升性能。 你可以把这种缓存操作委托给某个拦截器,而不破坏你现有的各个数据服务。
CachingInterceptor
演示了这种方式。
app/http-interceptors/caching-interceptor.ts)
content_copy@Injectable()
export class CachingInterceptor implements HttpInterceptor {
constructor(private cache: RequestCache) {}
intercept(req: HttpRequest<any>, next: HttpHandler) {
// continue if not cachable.
if (!isCachable(req)) { return next.handle(req); }
const cachedResponse = this.cache.get(req);
return cachedResponse ?
of(cachedResponse) : sendRequest(req, next, this.cache);
}
}
isCachable()
函数用于决定该请求是否允许缓存。 在这个例子中,只有发到 npm 包搜索 API 的 GET 请求才是可以缓存的。
如果该请求是不可缓存的,该拦截器只会把该请求转发给链表中的下一个处理器。
如果可缓存的请求在缓存中找到了,该拦截器就会通过 of()
函数返回一个已缓存的响应体的可观察对象,然后把它传给 next
处理器(以及所有其它下游拦截器)。
如果可缓存的请求在缓存中没找到,代码就会调用 sendRequest
。
content_copy/** * Get server response observable by sending request to `next()`. * Will add the response to the cache on the way out. */function sendRequest( req: HttpRequest<any>, next: HttpHandler, cache: RequestCache): Observable<HttpEvent<any>> { // No headers allowed in npm search request const noHeaderReq = req.clone({ headers: new HttpHeaders() }); return next.handle(noHeaderReq).pipe( tap(event => { // There may be other events besides the response. if (event instanceof HttpResponse) { cache.put(req, event); // Update the cache. } }) );}
sendRequest
函数创建了一个不带请求头的请求克隆体,因为 npm API 不会接受它们。
它会把这个请求转发给 next.handle()
,它最终会调用服务器,并且返回服务器的响应。
注意 sendRequest
是如何在发回给应用之前拦截这个响应的。 它会通过 tap()
操作符对响应进行管道处理,并在其回调中把响应加到缓存中。
然后,原始的响应会通过这些拦截器链,原封不动的回到服务器的调用者那里。
数据服务,比如 PackageSearchService
,并不知道它们收到的某些 HttpClient
请求实际上是从缓存的请求中返回来的。
返回多值可观察对象
HttpClient.get()
方法正常情况下只会返回一个可观察对象,它或者发出数据,或者发出错误。 有些人说它是“一次性完成”的可观察对象。
但是拦截器也可以把这个修改成发出多个值的可观察对象。
修改后的 CachingInterceptor
版本可以返回一个立即发出缓存的响应,然后仍然把请求发送到 NPM 的 Web API,然后再把修改过的搜索结果重新发出一次。
content_copy// cache-then-refresh
if (req.headers.get('x-refresh')) {
const results$ = sendRequest(req, next, this.cache);
return cachedResponse ?
results$.pipe( startWith(cachedResponse) ) :
results$;
}
// cache-or-fetch
return cachedResponse ?
of(cachedResponse) : sendRequest(req, next, this.cache);
这种缓存并刷新的选项是由自定义的 x-refresh
头触发的。
PackageSearchComponent
中的一个检查框会切换 withRefresh
标识, 它是 PackageSearchService.search()
的参数之一。search
()
方法创建了自定义的 x-refresh
头,并在调用 HttpClient.get()
前把它添加到请求里。
修改后的 CachingInterceptor
会发起一个服务器请求,而不管有没有缓存的值。 就像 前面 的 sendRequest()
方法一样进行订阅。 在订阅 results$
可观察对象时,就会发起这个请求。
如果没有缓存的值,拦截器直接返回 result$
。
如果有缓存的值,这些代码就会把缓存的响应加入到 result$
的管道中,使用重组后的可观察对象进行处理,并发出两次。 先立即发出一次缓存的响应体,然后发出来自服务器的响应。 订阅者将会看到一个包含这两个响应的序列。
监听进度事件
有时,应用会传输大量数据,并且这些传输可能会花费很长时间。 典型的例子是文件上传。 可以通过在传输过程中提供进度反馈,来提升用户体验。
要想开启进度事件的响应,你可以创建一个把 reportProgress
选项设置为 true
的 HttpRequest
实例,以开启进度跟踪事件。
app/uploader/uploader.service.ts (upload request)
content_copyconst req = new HttpRequest('POST', '/upload/file', file, {
reportProgress: true
});
每个进度事件都会触发变更检测,所以,你应该只有当确实希望在 UI 中报告进度时才打开这个选项。
接下来,把这个请求对象传给 HttpClient.request()
方法,它返回一个 HttpEvents
的 Observable
,同样也可以在拦截器中处理这些事件。
app/uploader/uploader.service.ts (upload body)
content_copy// The `HttpClient.request` API produces a raw event stream
// which includes start (sent), progress, and response events.
return this.http.request(req).pipe(
map(event => this.getEventMessage(event, file)),
tap(message => this.showProgress(message)),
last(), // return last (completed) message to caller
catchError(this.handleError(file))
);
getEventMessage
方法会解释事件流中的每一个 HttpEvent
类型。
app/uploader/uploader.service.ts (getEventMessage)
content_copy/** Return distinct message for sent, upload progress, & response events */
private getEventMessage(event: HttpEvent<any>, file: File) {
switch (event.type) {
case HttpEventType.Sent:
return `Uploading file "${file.name}" of size ${file.size}.`;
case HttpEventType.UploadProgress:
// Compute and show the % done:
const percentDone = Math.round(100 * event.loaded / event.total);
return `File "${file.name}" is ${percentDone}% uploaded.`;
case HttpEventType.Response:
return `File "${file.name}" was completely uploaded!`;
default:
return `File "${file.name}" surprising upload event: ${event.type}.`;
}
}
这个范例应用中并没有一个用来接收上传的文件的真实的服务器。 app/http-interceptors/upload-interceptor.ts
中的 UploadInterceptor
会拦截并短路掉上传请求,改为返回一个带有各个模拟事件的可观察对象。
安全:XSRF 防护
跨站请求伪造 (XSRF)是一个攻击技术,它能让攻击者假冒一个已认证的用户在你的网站上执行未知的操作。HttpClient
支持一种通用的机制来防范 XSRF 攻击。当执行 HTTP 请求时,一个拦截器会从 cookie 中读取 XSRF 令牌(默认名字为 XSRF-TOKEN
),并且把它设置为一个 HTTP 头 X-XSRF-TOKEN
,由于只有运行在你自己的域名下的代码才能读取这个 cookie,因此后端可以确认这个 HTTP 请求真的来自你的客户端应用,而不是攻击者。
默认情况下,拦截器会在所有的修改型请求中(比如 POST 等)把这个 cookie 发送给使用相对 URL 的请求。但不会在 GET/HEAD 请求中发送,也不会发送给使用绝对 URL 的请求。
要获得这种优点,你的服务器需要在页面加载或首个 GET 请求中把一个名叫 XSRF-TOKEN
的令牌写入可被 JavaScript 读到的会话 cookie 中。 而在后续的请求中,服务器可以验证这个 cookie 是否与 HTTP 头 X-XSRF-TOKEN
的值一致,以确保只有运行在你自己域名下的代码才能发起这个请求。这个令牌必须对每个用户都是唯一的,并且必须能被服务器验证,因此不能由客户端自己生成令牌。把这个令牌设置为你的站点认证信息并且加了盐(salt)的摘要,以提升安全性。
为了防止多个 Angular 应用共享同一个域名或子域时出现冲突,要给每个应用分配一个唯一的 cookie 名称。
注意,HttpClient
支持的只是 XSRF 防护方案的客户端这一半。 你的后端服务必须配置为给页面设置 cookie ,并且要验证请求头,以确保全都是合法的请求。否则,Angular 默认的这种防护措施就会失效。
配置自定义 cookie/header 名称
如果你的后端服务中对 XSRF 令牌的 cookie 或 头使用了不一样的名字,就要使用 HttpClientXsrfModule.withConfig()
来覆盖掉默认值。
content_copyimports: [
HttpClientModule,
HttpClientXsrfModule.withOptions({
cookieName: 'My-Xsrf-Cookie',
headerName: 'My-Xsrf-Header',
}),
],
测试 HTTP 请求
如同所有的外部依赖一样,HTTP 后端也需要在良好的测试实践中被 Mock 掉。@angular/common/http
提供了一个测试库 @angular/common/http/testing
,它让你可以直截了当的进行这种 Mock 。
Mock 方法论
Angular 的 HTTP 测试库是专为其中的测试模式而设计的。在这种模式下,会首先在应用中执行代码并发起请求。
然后,每个测试会期待发起或未发起过某个请求,对这些请求进行断言, 最终对每个所预期的请求进行刷新(flush)来对这些请求提供响应。
最终,测试可能会验证这个应用不曾发起过非预期的请求。
本章所讲的这些测试位于 src/testing/http-client.spec.ts
中。 在 src/app/heroes/heroes.service.spec.ts
中还有一些测试,用于测试那些调用了 HttpClient
的数据服务。
环境设置
要开始测试那些通过 HttpClient
发起的请求,就要导入 HttpClientTestingModule
模块,并把它加到你的 TestBed
设置里去,代码如下:
app/testing/http-client.spec.ts (imports)
content_copy// Http testing module and mocking controller
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
// Other imports
import { TestBed } from '@angular/core/testing';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
然后把 HTTPClientTestingModule
添加到 TestBed
中,并继续设置被测服务。
app/testing/http-client.spec.ts(setup)
content_copydescribe('HttpClient testing', () => {
let httpClient: HttpClient;
let httpTestingController: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule ]
});
// Inject the http service and test controller for each test
httpClient = TestBed.get(HttpClient);
httpTestingController = TestBed.get(HttpTestingController);
});
/// Tests begin ///
});
现在,在测试中发起的这些请求将会被这些测试后端(testing backend)处理,而不是标准的后端。
这种设置还会调用 TestBed.get()
,来获取注入的 HttpClient
服务和模拟对象的控制器 HttpTestingController
,以便在测试期间引用它们。
期待并回复请求
现在,你就可以编写测试,等待 GET 请求并给出模拟响应。
app/testing/http-client.spec.ts(httpClient.get)
content_copyit('can test HttpClient.get', () => {
const testData: Data = {name: 'Test Data'};
// Make an HTTP GET request
httpClient.get<Data>(testUrl)
.subscribe(data =>
// When observable resolves, result should match test data
expect(data).toEqual(testData)
);
// The following `expectOne()` will match the request's URL.
// If no requests or multiple requests matched that URL
// `expectOne()` would throw.
const req = httpTestingController.expectOne('/data');
// Assert that the request is a GET.
expect(req.request.method).toEqual('GET');
// Respond with mock data, causing Observable to resolve.
// Subscribe callback asserts that correct data was returned.
req.flush(testData);
// Finally, assert that there are no outstanding requests.
httpTestingController.verify();
});
最后一步,验证没有发起过预期之外的请求,足够通用,因此你可以把它移到 afterEach()
中:
content_copyafterEach(() => {
// After every test, assert that there are no more pending requests.
httpTestingController.verify();
});
自定义对请求的预期
如果仅根据 URL 匹配还不够,你还可以自行实现匹配函数。 比如,你可以验证外发的请求是否带有某个认证头:
content_copy// Expect one request with an authorization header
const req = httpTestingController.expectOne(
req => req.headers.has('Authorization')
);
和前面根据 URL 进行测试时一样,如果零或两个以上的请求匹配上了这个期待,它就会抛出异常。
处理一个以上的请求
如果你需要在测试中对重复的请求进行响应,可以使用 match()
API 来代替 expectOne()
,它的参数不变,但会返回一个与这些请求相匹配的数组。一旦返回,这些请求就会从将来要匹配的列表中移除,你要自己验证和刷新(flush)它。
content_copy// get all pending requests that match the given URL
const requests = httpTestingController.match(testUrl);
expect(requests.length).toEqual(3);
// Respond to each request with different results
requests[0].flush([]);
requests[1].flush([testData[0]]);
requests[2].flush(testData);
测试对错误的预期
你还要测试应用对于 HTTP 请求失败时的防护。
调用 request.flush()
并传入一个错误信息,如下所示:
content_copyit('can test for 404 error', () => {
const emsg = 'deliberate 404 error';
httpClient.get<Data[]>(testUrl).subscribe(
data => fail('should have failed with the 404 error'),
(error: HttpErrorResponse) => {
expect(error.status).toEqual(404, 'status');
expect(error.error).toEqual(emsg, 'message');
}
);
const req = httpTestingController.expectOne(testUrl);
// Respond with mock error
req.flush(emsg, { status: 404, statusText: 'Not Found' });
});
另外,你还可以使用 ErrorEvent
来调用 request.error()
.
content_copyit('can test for network error', () => {
const emsg = 'simulated network error';
httpClient.get<Data[]>(testUrl).subscribe(
data => fail('should have failed with the network error'),
(error: HttpErrorResponse) => {
expect(error.error.message).toEqual(emsg, 'message');
}
);
const req = httpTestingController.expectOne(testUrl);
// Create mock ErrorEvent, raised when something goes wrong at the network level.
// Connection timeout, DNS error, offline, etc
const mockError = new ErrorEvent('Network error', {
message: emsg,
});
// Respond with mock error
req.error(mockError);
});
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com