问题陈述
我对 Angular 4 非常陌生,正在努力寻找如何在 token 过期时让用户重新登录。
让我们深入研究代码
我有一个响应拦截器
,用于检查响应代码是否有401
错误
intercept(request: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
return next.handle(request).do(
// success responses
(event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// I do not want to do anything here... just pass
}
},
// error responses
(err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
//here is where I need to show a modal
//OH! STACKOVER-FLOW PLEASE BLESS ME
}
}
});
}
只是通知
该应用程序过于模块化,因为每个组件
本身就是一个模块。就像一个例子:Login Component
本身就是一个模块,Registration
是另一个使用路由包含在根模块中的模块...
那么你能帮我找到解决这个谜题的最佳实践吗?
最佳答案
我正在使用Angular4 CanActivate检查用户是否登录,我认为它的工作方式与您的方法相同。 无论如何,在您的 canActivate 服务或您的钩子(Hook)内部,我可以看到 2 个解决方案:
1) 正如@Sajal 提到的 - 广播事件:
@Injectable()
export class YourService {
heyStopRightThere: EventEmitter<boolean> = new EventEmitter();
intercept(request: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
...
if (err.status === 401) {
this.heyStopRightThere.emit();
}
...
}
}
然后在所有 protected 组件中
constructor(
private _yrSvc: YourService
) {
}
showLoginDialog() {
//enable component LoginDialog that embeded in
// <loginDialog *ngIf="notLoggedIn"></loginDialog>
}
ngOnInit() {
this._yrSvc.heyStopRightThere.subscribe(() =>
showLoginDialog()
);
}
2)使用参数重定向到回调:
@Injectable()
export class YourService {
constructor(private router: Router){}
intercept(request: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
...
if (err.status === 401) {
this.router.navigate(['/login', {callback: location.href}]);
}
...
}
然后您可以在登录组件中绘制对话框并在成功时重定向回“回调”。
关于javascript - Angular 4 : How to show Re-login Dialog/Modal from intercepter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47049999/