我正在尝试在angular v10中测试一个http拦截器,但是上手时遇到了麻烦。拦截器接收http请求并触发微调器(loadService),直到响应返回。我有一个看起来像这样的拦截器。我读过的大多数拦截器文章都大多带有标头的拦截器,而没有。
removeRequest(req: HttpRequest<any>) {
const i = this.requests.indexOf(req);
if (i >= 0) {
this.requests.splice(i, 1);
}
this.loaderService.isLoading.next(this.requests.length > 0);
}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
this.requests.push(req);
this.loaderService.isLoading.next(true);
return new Observable((observer) => {
const subscription = next.handle(req).subscribe(
(event) => {
if (event instanceof HttpResponse) {
this.removeRequest(req);
observer.next(event);
}
},
(err) => {
this.removeRequest(req);
observer.error(err);
},
() => {
this.removeRequest(req);
observer.complete();
}
);
// remove request from queue when cancelled
return () => {
this.removeRequest(req);
subscription.unsubscribe();
};
});
}
有人可以帮助我指出正确的方向吗?
答案 0 :(得分:0)
您做对了!
您只是在拦截功能上犯了一个错误,请执行以下操作:
intercept(req: HttpRequest<any>, next: HttpHandler) {
let updatedRequest: HttpRequest<any>;
updatedRequest = req.clone(//Add headers here);
this.loaderService.isLoading.next(true);
//Add the request at the array
this.requests.push(updatedRequest);
//You don't need to return new Observable, just handle with 'next' and pipes
return next.handle(updatedRequest).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status >= 500) {
console.log('error', error);
}
this.removeRequest(updatedRequest);
return throwError(error);
}),
finalize(() => {
this.removeRequest(updatedRequest);
})
);
}