我想在一个组件中为我的HTTP请求检测到401响应代码:
@Injectable()
export class InterceptorProvider implements HttpInterceptor {
constructor(private authService: AuthenticationService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log(request);
return next.handle(request);
}
如何在响应代码正常的情况下捕获错误,执行刷新令牌请求并让其他组件继续运行?
更新
@Injectable()
导出类InterceptorProvider实现HttpInterceptor {
constructor(private authService: AuthenticationService, private storage: Storage) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log(request);
return next.handle(request)
.pipe(tap(event => {
if (event instanceof HttpResponse) {
}
}, err => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
console.log(err);
console.log("Retriving user....");
let user = new User();
this.storage.get('username').then((result)=>{
console.log(result);
user.username = result;
let pass = this.storage.get('password').then((result)=>{
console.log(result);
user.password = result;
console.log(user.username);
console.log(user.password);
console.log("user ok");
this.authService.login(user.username, user.password).toPromise().then(response=>{
let token = response['message'];
this.storage.set('token', token);
this.addToken(request, token);
return next.handle(this.addToken(request, token));
});
});
});
}
}
})
)
}
// Adds the token to your headers if it exists
private addToken(request: HttpRequest<any>, token: any) {
if (token) {
let clone: HttpRequest<any>;
clone = request.clone({
setHeaders: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: token
}
});
return clone;
}
return request;
}
}
这个新版本进行了重新登录操作,但是并没有进一步进行,重新添加原始访问令牌的原始请求的重新执行似乎有些问题;我在哪里错了?
更新
这是控制台错误:
core.js:9110 ERROR Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":401,"statusText":"Unauthorized","url":"https://www.fantacalciopizza.it/php/formazioniinviatejson2.php","ok":false,"name":"HttpErrorResponse","message":"Http failure response for https://www.fantacalciopizza.it/php/formazioniinviatejson2.php: 401 Unauthorized","error":"\n\n"}
at resolvePromise (zone-evergreen.js:797)
at resolvePromise (zone-evergreen.js:754)
at zone-evergreen.js:858
at ZoneDelegate.invokeTask (zone-evergreen.js:391)
at Object.onInvokeTask (core.js:34182)
at ZoneDelegate.invokeTask (zone-evergreen.js:390)
at Zone.runTask (zone-evergreen.js:168)
at drainMicroTaskQueue (zone-evergreen.js:559)
at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:469)
at invokeTask (zone-evergreen.js:1603)
然后尝试登录,我得到了响应,但是克隆的请求似乎没有被执行;我在哪里错了?
答案 0 :(得分:1)
尝试这样:
return next.handle(authRquest)
.pipe(
tap(event => {
if (event instanceof HttpResponse) {
}
}, err => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
// handle error
}
}
})
)
答案 1 :(得分:0)
我通常在拦截器上执行此操作
return next.handle(req).pipe(
tap<HttpResponse<any>>(
res => {
// Logic if response is ok
},
err => {
// Logic if response is not ok
if(err.status === 401) {
// Handle the error
}
}
)
)
答案 2 :(得分:0)
在根模块的提供者中注册 UnauthorizedInterceptor 后,它将自动检测到401,403错误
在未经授权的拦截器中
@Injectable()
export class UnauthorizedInterceptor implements HttpInterceptor {
constructor() { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(err => {
if ([401, 403].indexOf(err.status) !== -1) {
// YOUR MESSAGE
}
const error = err || err.statusText;
return throwError(error);
}))
}
}
在AppModule.ts中
@NgModule({
...,
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: UnauthorizedInterceptor,
multi: true
}]
})