Auth guard not working in angular 5

Melvin picture Melvin · Dec 9, 2017 · Viewed 8.7k times · Source

Here is my static login service

login(email: string, password: string) {
debugger;
const user = {
  username: email,
  password: password,

};
if (email === "admin" && password === "admin") {
  localStorage.setItem("currentUser", JSON.stringify(user));
}
if (localStorage.getItem("currentUser")) {
  // logged in so return true
  return user;
} else {
  return false;
}
}

My authguard service

  export class AuthGuard implements CanActivate {
  constructor(private router: Router) {


  }
        isAuthenticated(): boolean{
      if (localStorage.getItem("currentUser")) {
        return true;
      }
      else{
        return false;
      }
    }

    canActivate(): boolean {
      if (!this.isAuthenticated()) {
        this.router.navigate(['login']);
        return false;
      }
      return true;
    }
}

my app.routing.ts

const appRoutes: Routes = [
  { path: "home", component: HomeComponent ,canActivate: [AuthGuard]},
  { path: "login", component: AuthComponent },
  { path: "", component: AuthComponent },
  { path: "employees", component: EmpComponent,canActivate: [AuthGuard] },
  // otherwise redirect to home
  { path: "**", redirectTo: "/" }
];

app.module.ts

@NgModule({
  declarations: [AppComponent, HeaderComponent, FooterComponent],
  imports: [
    BrowserModule,
    FormsModule,
    SharedModule,
    HomeModule,
    AuthModule,
    EmpModule,
    routing,
    Ng4LoadingSpinnerModule,
    AlertModule.forRoot()
  ],
  providers: [AuthGuard, AuthenticationService],
  schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
  bootstrap: [AppComponent]
})

I just tested this by entering a route directly in browser url for example /home which has canactivate enabled in its route config but when i do so the home contents are displayed instead of redirecting to the login page.Need too know what's wrong here any help will be really appreciated thanks in advance :)

Answer

Sajeetharan picture Sajeetharan · Dec 9, 2017

There is no issue with your current code, if you have routing for each component separately, remove them and have them only in the app.module.ts