angular - 在 HttpInterceptor 上捕获取消/中止请求。角8
问题描述
我在使用 Angular 8 构建的应用程序中遇到问题。
我有一个应用程序级微调器,它会为每个发出的 http 请求打开并在响应中关闭。
这些请求由显示负载微调器的 HttpInterceptor 捕获,并在获得响应时将其隐藏。当其中一些 http 调用被取消时,问题就出现了,如下例所示:
search(param: string) {
return terms.debounceTime(SEARCH_DEBOUNCE)
.distinctUntilChanged()
.switchMap(term => this.search(param));
}
上面的代码属于一个文本搜索引擎,当你停止输入一段时间后,就会执行搜索。当这完成得太快时,可以同时发出多个请求,然后 switchMap 会取消这些请求。出于这个原因,当请求被取消时,拦截器无法获得取消的状态,因此微调器永远不会消失。
拦截器做这样的事情:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<any> {
// the spinner is shown
return next.handle(request).pipe(
catchError(error => {
// error handling and spinner stop
}),
finalize(() => {
// Access to all responses except cancelled requests, which have no response.
})
);
因此,对于那些请求被取消或中止的情况,我无法停止微调器。
解决方案
如果您的目标是在没有任何特定条件的情况下停止微调器,而只是在 return 语句中,您可以像这样使用点击运算符(https://rxjs-dev.firebaseapp.com/api/operators/tap):
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<any> {
// the spinner is shown
return next.handle(request).pipe(
catchError(error => {
// Do things
}),
finalize(() => {
// Do things
}),
tap(()=> /* stop spinning */)
);
推荐阅读
- corda - Corda V4 合同和流测试用例在 Windows 上的 IntelliJ 中运行
- javascript - axiosjs 从节点发送 FormData
- php - PHP 合并数组
- mongodb - 如何查询多个MongoDB集合?
- scroll - 同步滚动多个可滚动小部件
- python - input() 将一个答案与另一个答案联系起来
- php - 用php代码解决税收问题的数学公式
- javascript - 如何检查对象是一个集合?
- java - JAVA:如何将多个成员添加到 LDAP 中的组
- javascript - 我们是否*必须*使用 data: URIs (readAsDataURL)在 JavaScript中使用 File 对象?