Angular 如何处理HttpInterceptor中的HTTP状态?
我对POST请求使用添加选项:Angular 如何处理HttpInterceptor中的HTTP状态?,angular,Angular,我对POST请求使用添加选项: return this.http.post("", data, { observe: "response" }); 当我尝试在拦截器中处理此响应时,我无法获取http状态: return next.handle(request).pipe( map((event: any) => { console.log(event.status); return event; }); 在管道内使用catchError,
return this.http.post("", data, { observe: "response" });
当我尝试在拦截器中处理此响应时,我无法获取http状态:
return next.handle(request).pipe(
map((event: any) => {
console.log(event.status);
return event;
});
在管道内使用catchError,如下所示:
.pipe(
catchError(err => { // catch response error from server
if (err instanceof HttpErrorResponse) {
switch ((<HttpErrorResponse>err).status) {
case 401: // if is 401 error
}
}
})
);
.pipe(
catchError(err=>{//catch服务器响应错误
if(HttpErrorResponse的错误实例){
开关((错误)。状态){
案例401://如果是401错误
}
}
})
);
您不需要实际观察响应。您可以删除{observe:“response”}。
在拦截器中处理它所需要的就是将catchError添加到管道中。要避免错误(如果您希望请求以成功结束)您应该返回catchError中某个内容的可观察值。
您还可以通知用户或对某些错误执行某些操作,如上面显示的Klodian
return next.handle(request).pipe(
catchError(error => {
if (error instanceof HttpErrorResponse) {
// notify user or perfome actions
}
return of([]); // return empty Observable of array
}),
map((event: any) => {
console.log(event.status);
return event;
});
@OPV-我是通过搜索你评论的确切文本到达那里的。也就是说,这取决于BE的实现。有些API每样东西都返回200(这不是标准,但人们会这样做)。