I am currently working on setting up User Authentication for a website backend using Angular 2. However, I have encountered some issues that I am struggling to resolve. Here is an overview of my approach.
Below is my routing file:
const appRoutes: Routes = [
{
path: 'admin',
component: AdminloginComponent,
canActivate: [LoggedInGuard]
},
{
path: '',
component: HomepageComponent
},
{
path: '**',
component: OurservicesComponent
},
];
In the guard file, after a successful login, I set the "is_logged_in" flag in local storage:
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
@Injectable()
export class LoggedInGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if(localStorage.getItem("is_logged_in"))
{
this.router.navigate(['/admin/dashboard']);
return true;
}
return false;
}
*
My current issue arises when the URL is "/admin", triggering the canActivate method. If there is no data stored in the local storage indicating that the user is logged in, it redirects to "/admin/dashboard". However, I want to display a login form at "/admin" when the user is not logged in. Finding a solution to this problem is proving challenging. Any suggestions would be greatly appreciated.
Thank you in advance.