我的登录服务(用Django编写),当用户未经授权时返回{"message":{"password":["invalid user name or password !"]},"status":111}
,但是http请求返回的状态码为200,因此请求转到成功块而不是错误块。
我的问题是,根据响应内返回的状态码,有什么方法可以在错误块中捕获错误。
答案 0 :(得分:1)
您需要创建一个拦截器。了解如何创建拦截器here
在拦截器中,您可以执行以下操作。拦截响应,检查您的状况并相应地引发错误。
export class YourInterceptor implements HttpInterceptor{
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{
//check for your condition here, if true, return error as follows. This will run your error block.
return Observable.throw(new HttpErrorResponse({status:401, statusText:"Error of auth"}));
}
}
有了Angular 6和(rxjs 6),您现在就可以这样做
intercept(req: HttpRequest, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(tap((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) //Check if it is a response
{
if(your condition here) //hint: Use event object to get your response
{
throwError('Your error')
}
}
return event;
}));
}