2017-03-18 120 views
3

当用户没有登录我的应用程序时,它等于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。这意味着...根应用程序组件继续运行之后的代码。

+0

你应该在导航之前移除令牌叫我想?会有曲线重定向可能是 –

+0

而你在根组件中执行它不正确,它将只执行一次,因为该应用程序被加载使用canActivate这个https://angular.io/docs/ts/latest/api/router /index/CanActivate-interface.html –

+0

好吧,但是当我订阅路由应用程序组件中的更改时,它应该可以正常工作。我只是尝试一下! – Pascal

回答

1

到角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

+0

我想过这个,但不想把10个激活方法无处不在...而是一个地方更整洁 - 如果它的工作 - – Pascal

+0

你的意思是你想在许多路线中使用? –

+0

我只是想在一个地方做一次isLoggedIn调用,只要路由发生变化。 – Pascal

0

此代码将无法工作。

if (!authService.isLoggedIn()) 
{ 
    this.router.navigate(['/login']); 
} 

您应该调用服务来预先授权用户。但是您正在检查尚未定义的服务状态。

+0

创建authService实例,没有问题。 – Pascal

+0

而且这将只会执行一次,因为应用程序启动 –

+0

,你想说什么? –