You should try canActivate. It will identify user loged-in and based on enable routes. Below is example. Create ts file for below.
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
@Injectable()
export class UserAuthorised implements CanActivate {
constructor(private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (your condition here of if login true) {
return true;
} else {
//redirect to login page.
this.router.navigate(['/login']);
return false;
}
}
}
Add above entry into list of providers in app.module.ts file. Now this class reference you need to give in routes file.
{ path: 'dashboard', component: DashboardComponent, canActivate: [UserAuthorised] },
What above will do : If user tries to access url directly routes will return false and redirect user to login page.