如果我的请求未得到授权,如何重定向到登录页面?现在有一个模态告诉用户尚未登录。 I've found some answers but they used MVC.谢谢。
答案 0 :(得分:0)
您可以使用拦截器服务来解决此问题,它将始终检查任何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) {}