I am trying to create a website backend for which I need User Authentication in Angular 2. But I am unable to resolve some of issue, this is what I am doing.
This is my routing file.
const appRoutes: Routes = [
{
path: 'admin',
component: AdminloginComponent,
canActivate: [LoggedInGuard]
},
{
path: '',
component: HomepageComponent
},
{
path: '**',
component: OurservicesComponent
},
];
This is my gaurd file: // after successfull login i am setting is_logged_in 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 issue is that when the url is /admin canActivate comes into action and if I get local storage I am navigating to admin/dashboard.
But if user is logged out then in this case on /admin their should be loginform, but if I navigate to /admin if not logged in then it comes into canActivate and again their is nothing in local storage so it goes to admin and so on. So what is the correct way to solve this.
Thanks in advance.