如果我的请求未获得授权,如何重定向到登录页面?现在有一个模态告诉用户尚未登录。 I've found some answers but they used MVC.谢谢。
您可以使用拦截器服务来解决此问题,它将始终检查是否有任何API失败,如果它失败,那么您可以将其重定向到登录屏幕
@Injectable()
export class HttpInterceptor extends Http {
public flag = false;
constructor(
backend: XHRBackend,
options: RequestOptions,
public http: Http, private router: Router, private tr:ToastrService
) {
super(backend, options);
}
public request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
return super.request(url, options)
.catch(this.handleError);
}
public handleError = (error: Response) => {
// Do messaging and error handling here
const errorresponse = (<any>error)._body;
if(localStorage.getItem('token') !== null && error.statusText) {
if(errorresponse.toUpperCase().includes('FORBIDDEN')) {
alert('Token is expired you need to login again');
localStorage.clear();
window.location.reload();
this.router.navigateByUrl('/');
return Observable.throw(error);
}
}else if(error.statusText === '' && this.flag) {
this.tr.error('', 'Network Issue');
this.flag = false;
}
}
}
在每个service.ts文件中添加此项
constructor(private http: HttpInterceptor, private us: UserService) {}