响应的 Http 拦截器在 angular 5 中不起作用
Http interceptor on response not working in angular 5
我希望用户在出现 api returns 401 错误时自动注销 response.And 我正在拦截每个请求,一旦错误代码出现401 我正在清除本地存储中的 jwt 令牌,并且 auth guard 阻止用户在实施拦截器后跳转到那个 route.But(这方面的例子非常少,文档中也没有提及)我无法命中任何 HTTP request.Below 是我的 code.Thanks 提前。
import { Injectable, Injector } from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse} from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/throw'
import 'rxjs/add/operator/catch';
@Injectable()
export class ResponseInterceptor implements HttpInterceptor {
constructor() {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).do((event: HttpEvent<any>) => {
}, (err: any) => {
if (err instanceof HttpErrorResponse) {
// do error handling here
console.log('and the error is ');
console.log(err)
}
});
}
}
如果出现错误为什么你需要跟踪每个请求如果你只能catch 需要吗?
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
catchError((err:string, caught:Observable<any>)=>this.handleHttpClientError(err, caught))
);
}
handleHttpClientError(error: any, caught: Observable<any>)
{
if(error.status == 401){
... your logic here ...
}
return new EmptyObservable<Response>();
// or return Observable.throw('Auth error');
}
我希望用户在出现 api returns 401 错误时自动注销 response.And 我正在拦截每个请求,一旦错误代码出现401 我正在清除本地存储中的 jwt 令牌,并且 auth guard 阻止用户在实施拦截器后跳转到那个 route.But(这方面的例子非常少,文档中也没有提及)我无法命中任何 HTTP request.Below 是我的 code.Thanks 提前。
import { Injectable, Injector } from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse} from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/throw'
import 'rxjs/add/operator/catch';
@Injectable()
export class ResponseInterceptor implements HttpInterceptor {
constructor() {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).do((event: HttpEvent<any>) => {
}, (err: any) => {
if (err instanceof HttpErrorResponse) {
// do error handling here
console.log('and the error is ');
console.log(err)
}
});
}
}
如果出现错误为什么你需要跟踪每个请求如果你只能catch 需要吗?
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
catchError((err:string, caught:Observable<any>)=>this.handleHttpClientError(err, caught))
);
}
handleHttpClientError(error: any, caught: Observable<any>)
{
if(error.status == 401){
... your logic here ...
}
return new EmptyObservable<Response>();
// or return Observable.throw('Auth error');
}