TheUnreal
TheUnreal

Reputation: 24472

Angular 2 authentication: logout stays in the user page

My app has 2 features: AppModule, and UserModule.

UserModule - for logged in users.

AppModule - login page.

I manage my auth in my auth.service and I also have guard as auth.guard.service.

When I call auth.service.logOut(), the user is logged out, but stays in the panel and route is not changing. I also tried to add this.router.navigate(['']); but the user stays in the /panel route.

This is my logout method:

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

I call this method inside my PanelComponent. The problem is that the user stays in the PanelComponent, and is not "kicked out" back to the login page, which is the HomeComponent.

app.routing.module.ts

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

user-panel.routing.module.ts

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

When I refresh my page, I'm transfered back to the login. why it doesn't work without refreshing?

Update: My home redirects me back to the panel, although the isLoggedIn variable has changed.

my HomeComponent is redirecting me back to my panel although it shouldn't.

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']);
      }
    });

in my logOut() method I set my isLoggedIn variable to false. Although, my console outputs Navigated back to worker panel!

Upvotes: 3

Views: 7630

Answers (1)

ranakrunal9
ranakrunal9

Reputation: 13558

Change your parent router as below and use this.router.navigate(['home']); in your logout function

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

Upvotes: 2

Related Questions