我正在尝试创建一个拦截器,该拦截器应在返回401错误时调用函数以刷新会话。到目前为止,这是我所拥有的,但无法建立,我无法解决该怎么做:
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
request = request.clone({
withCredentials: true
});
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
return this.userAPI
.refreshSession(this.authService.getRefreshToken())
.then(res => {
this.authService.setAuthenticated(false);
return next.handle(request);
});
} else {
this.authService.setAuthenticated(false);
}
})
);
}
VS代码报告:
Type 'Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any> | Observable<HttpEvent<any>>>' is not assignable to type 'Observable<HttpEvent<any>>'.
答案 0 :(得分:1)
catchError
必须返回一个可观察值。尝试以下操作或类似操作:
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
request = request.clone({
withCredentials: true
});
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
return this.userAPI
.refreshSession(this.authService.getRefreshToken())
.then(res => {
this.authService.setAuthenticated(false);
return next.handle(request);
});
} else {
this.authService.setAuthenticated(false);
// Add this
return next.handle(request);
}
})
);
}