当用户未登录我的应用程序时,该应用程序等于没有“用户提示”的用户。在localStorage中,我只想将他重定向到登录路线。
假设用户输入了路由/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。这意味着......根应用程序组件之后的代码继续运行。
答案 0 :(得分:1)
角度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
答案 1 :(得分:0)
此代码永远不会有效。
if (!authService.isLoggedIn())
{
this.router.navigate(['/login']);
}
您应该先调用该服务以预先授权用户。但是您正在检查尚未定义的服务状态。