当用户未登录到我的应用程序时,这等于 localStorage 中不存在 userToken
那么我只想将他重定向到登录路径。
假设用户输入路径 /customers
,当本地存储中不存在 userToken
时,他应该被重定向到登录屏幕。
App.component.ts
:
export class AppComponent
{
constructor(private routerService: RouterService, private router: Router, private authService: AuthenticationService)
{
if (!authService.isLoggedIn())
{
this.router.navigate(['/login']);
}
}
}
路由器导航方法被调用但它没有导航到登录屏幕,为什么不呢?尝试获取后端的客户数据,但我在服务器响应中收到 401。这意味着......根应用程序组件之后的代码继续运行。
最佳答案
Angular 2 检查用户的最佳方法是在通过路由之前登录或不登录。您可以在路由定义中使用“canActivate”,如下所示
{ path: 'customers', component: AppComponent, canActivate: [AuthService] }
现在在 AuthService 上你可以定义方法
canActivate() {
//you can check token is exists or not here
if (localstorage.getItem('user')) {
return true;
} else {
this.router.navigate(['login']);
return false;
}
}
更多详情 h ttps://blog.thoughtram.io/angular/2016/07/18/guards-in-angular-2.html
关于angular - 无法取消当前导航并从根组件导航到其他地方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42874979/