2016-10-17 49 views
2

我的应用程序有两个功能:AppModule和UserModule。Angular 2身份验证:注销保留在用户页面

UserModule - 用于登录用户。

AppModule - 登录页面。

我在我的auth.service中管理我的身份验证,我也有警卫auth.guard.service

当我拨打auth.service.logOut()时,用户已注销,但仍停留在面板中,路由不会改变。 我也尝试添加this.router.navigate(['']);,但用户停留在/panel路线中。

这是我的注销方法:

logout() { 
     console.log("logging out.."); 
     this.auth.logout(); 
     this.userData = null; 
    this.isLoggedIn = false; 
    this.router.navigate(['']); 
    } 

我打电话给我的PanelComponent这里面方法。问题在于用户停留在PanelComponent中,并且未被“踢出”回登录页面,即HomeComponent

app.routing.module.ts

@NgModule({ 
    imports: [ 
    RouterModule.forRoot([ 
     { path: '', component: HomeComponent }, 
    ]) 
    ], 
    exports: [ 
    RouterModule 
    ] 
}) 

用户panel.routing.module.ts

@NgModule({ 
    imports: [ 
    RouterModule.forChild([ 
     { 
     path: 'panel', 
     component: PanelComponent, 
     canActivate: [AuthGuard], 
     children: [ 
      { 
      path: '', 
      children: [ 
       { path: 'userHome', component: userHomeComponent }, 
       { path: '', component: PanelHomeComponent } 
      ] 
      } 
     ] 
     } 
    ]) 
    ], 

当我刷新我的网页,我转移到登陆。为什么它不工作而不提神清爽?

更新:尽管isLoggedIn变量已更改,但我的家将我重定向回面板。

我的HomeComponent重定向到我的面板,但它不应该。

HomeComponent:

ngOnInit() { 
     //If he is alredy logged, redirect him to the panel 
     this.authService.login().subscribe(() => { 
      this.loaded = true; 
     if (this.authService.isLoggedIn) { 
      console.log("Navigated back to worker panel!"); 
     this.router.navigate(['/worker-panel']); 
     } 
    }); 

在我退出()方法,我在我的isLoggedIn变量设置为false。虽然,我的控制台输出Navigated back to worker panel!

+0

请添加路由器的配置。 –

+0

嘿@GünterZöchbauer我添加了我的面板模块路由器。我将AuthGuard放入了两个模块(功能) – TheUnreal

+0

当您调用'auth.service.logOut()'时,哪条路由处于活动状态。预期的行为是什么?请添加父路由器配置。 –

回答

1

你的母路由器更改如下,并在您注销功能使用this.router.navigate(['home']);

RouterModule.forRoot([ 
    { 
    path: '', 
    redirectTo: '/home', 
    pathMatch: 'full' 
    }, 
    { path: 'home', component: HomeComponent }, 
])