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 :)
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
if you re using the route guard add it inside root app.module or what ever module.ts file
providers: [AuthGuard]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With