无法取消当前导航并从根组件导航到其他地方
问题描述:
当用户没有登录我的应用程序时,它等于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。这意味着...根应用程序组件继续运行之后的代码。
答
到角2检查用户最好的办法是登录或没有之前经历route.you可以在航线使用“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
答
此代码将无法工作。
if (!authService.isLoggedIn())
{
this.router.navigate(['/login']);
}
您应该调用服务来预先授权用户。但是您正在检查尚未定义的服务状态。
你应该在导航之前移除令牌叫我想?会有曲线重定向可能是 –
而你在根组件中执行它不正确,它将只执行一次,因为该应用程序被加载使用canActivate这个https://angular.io/docs/ts/latest/api/router /index/CanActivate-interface.html –
好吧,但是当我订阅路由应用程序组件中的更改时,它应该可以正常工作。我只是尝试一下! – Pascal