[英]Redirect to logout after Error on Request
我已经将应用程序从angular 2迁移到angular 5,并且也从不推荐使用的Http迁移到了新的HttpClient。
在旧的应用程序中,我使用以下Http-Client从错误重定向到特定页面。
import {Router} from "@angular/router"; import {Injectable} from "@angular/core"; import {ConnectionBackend, Http, Request, RequestOptions, RequestOptionsArgs, Response} from "@angular/http"; import {Observable} from "rxjs/Observable"; import "rxjs/add/operator/catch"; @Injectable() export class HttpService extends Http { constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private router: Router) { super(backend, defaultOptions); } request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> { return super.request(url, options) .catch(this.catchErrors()); } private catchErrors() { return (res: Response) => { if (this.isError(res)) { console.log(`Internal server error occured (${res.status} - ${res.statusText})`); this.router.navigateByUrl('/error'); } else if (this.isUnauthorized(res)) { console.log(`User is not authenticated - not logged in or the session expired? (${res.status} - ${res.statusText})`); this.router.navigateByUrl('/logout'); } else if (this.isForbidden(res)) { console.log(`User does not have necessary permissions for the resource (${res.status} - ${res.statusText}): ${res.url}`); this.router.navigateByUrl('/forbidden'); } return Observable.throw(res); }; } private isError(res: Response): boolean { return res && res.status === 500; } private isUnauthorized(res: Response): boolean { return res && res.status === 401; } private isForbidden(res: Response): boolean { return res && res.status === 403; } }
现在,我已经将此重构为HttpInterceptor
import {Router} from "@angular/router"; import {Injectable} from "@angular/core"; import {Observable} from "rxjs/Observable"; import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from "@angular/common/http"; @Injectable() export class HttpService implements HttpInterceptor { constructor(private router: Router) { } private catchErrors() { return (res: HttpResponse<any>) => { if (this.isError(res)) { console.log(`Internal server error occured (${res.status} - ${res.statusText})`); this.router.navigateByUrl('/error'); } else if (this.isUnauthorized(res)) { console.log(`User is not authenticated - not logged in or the session expired? (${res.status} - ${res.statusText})`); this.router.navigateByUrl('/logout'); } else if (this.isForbidden(res)) { console.log(`User does not have necessary permissions for the resource (${res.status} - ${res.statusText}): ${res.url}`); this.router.navigateByUrl('/forbidden'); } return Observable.throw(res); }; } private isError(res: HttpResponse<any>): boolean { return res && res.status === 500; } private isUnauthorized(res: HttpResponse<any>): boolean { return res && res.status === 401; } private isForbidden(res: HttpResponse<any>): boolean { return res && res.status === 403; } intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(req).catch(this.catchErrors()); } }
但是现在NavigationByUrl无效,甚至可以访问该站点。
有谁知道如何解决这个问题?
您可以尝试使用此解决方案
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const started = Date.now();
/**
* Handle newly created request with updated header (if given)
*/
return next.handle(req).do((event: HttpEvent<any>) => {
/**
* Sucessfull Http Response Time.
*/
if (event instanceof HttpResponse) {
const elapsed = Date.now() - started;
}
}, (err: any) => {
/**
* redirect to the error_handler route according to error status or error_code
*/
if (err instanceof HttpErrorResponse) {
switch (err.status) {
case 500:
console.log(`Internal server error occured (${err.status} - ${err.statusText})`);
this.router.navigateByUrl('/error');
break;
case 400:
console.log(`User is not authenticated - not logged in or the session expired? (${err.status} - ${err.statusText})`);
this.router.navigateByUrl('/logout');
break;
case 403:
console.log(`User does not have necessary permissions for the resource (${err.status} - ${err.statusText}): ${err.url}`);
this.router.navigateByUrl('/forbidden');
break;
}
}
});
}
您没有收到任何控制台错误消息?
我会尝试以下代码:
import {Router} from "@angular/router";
import {Injectable} from "@angular/core";
import {Observable} from "rxjs/Observable";
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from "@angular/common/http";
@Injectable()
export class HttpService implements HttpInterceptor {
constructor(private router: Router) {
}
private catchErrors(httpError) {
if (this.isError(res)) {
console.log(`Internal server error occured (${res.status} - ${res.statusText})`);
this.router.navigateByUrl('/error');
} else if (this.isUnauthorized(res)) {
console.log(`User is not authenticated - not logged in or the session expired? (${res.status} - ${res.statusText})`);
this.router.navigateByUrl('/logout');
} else if (this.isForbidden(res)) {
console.log(`User does not have necessary permissions for the resource (${res.status} - ${res.statusText}): ${res.url}`);
this.router.navigateByUrl('/forbidden');
}
return Observable.throw(res);
}
private isError(res: HttpResponse<any>): boolean {
return res && res.status === 500;
}
private isUnauthorized(res: HttpResponse<any>): boolean {
return res && res.status === 401;
}
private isForbidden(res: HttpResponse<any>): boolean {
return res && res.status === 403;
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).catch(httpError => this.catchErrors(httpError));
}
}
您需要确保将catchErrors
函数绑定到HttpService
类,并执行Observable.throw
以返回失败的Observable
。
还要检查Angular 6+中的httpError
类型,我正在使用HttpErrorResponse
但是我不确定较旧版本上的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.