I've implemented an HttpInterceptor
that adds a header to each requests and redirects to the login page if server responded with 401
. I don't want it to do anything else.
I'm noticing however that whenever I get a bad response from the server (as I expect it), the interceptor kicks it and throws the HttpErrorResponse
. However in my controller I get only a TypeError
object without the details from the server.
I'm attaching the relevant code.
Interceptor
@Injectable()
export class HttpAuthorizationService implements HttpInterceptor {
constructor(private cookieService: CookieService, private angularRouter: Router) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
req = req.clone({
setHeaders: {
Authorization: 'Bearer ' + this.cookieService.get('Authorization')
}
});
return next.handle(req).do((ev: HttpEvent<any>) => {})
.catch(error => {
if (error instanceof HttpErrorResponse) {
if (error.status === 401) {
this.cookieService.set('expired', 'Session expired');
this.angularRouter.navigate(['/login']);
}
}
return Observable.throw(error); <-- i think this is bad
});
}
}
and actual controller
deleteCategory(category) {
this.confirmationService.confirm({
message: 'Are you sure you want to delete?',
header: 'Delete product category ' + category,
icon: 'fa fa-trash',
accept: () => {
this.productService.deleteCategory(category).subscribe(
success => {
this.msgs = [{ severity: 'success', summary: 'Success', detail: 'Successfully deleted the product category ' + category }];
},
error => {
this.categories.push(category);
this.msgs = [{ severity: 'error', summary: 'Could not delete category', detail: error.status + '-' + error.error }]; <-- getting object without error attribute and no info from the server
}
);
},
reject: () => this.categories.push(category)
});
}
My question is how to i keep the original error object instead of what im actually getting if i don't implements this HttpInterceptor than my controllers gets the normal error object
我必须将另一个导入添加到我的HttpInterceptor实现中
import 'rxjs/add/observable/throw';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.