The best way to do this and with routes and route safekeeping would be thus in the route guard you put
export class AuthGuard implements CanActivate {
constructor(
private ahthSevice: AuthService,
private _router: Router
) { }
canActivate(
route:ActivatedRouteSnapshot,
state:RouterStateSnapshot
):Observable<boolean>|boolean{
if(this.ahthSevice.getUsuarioAutenticado()){
return true;
}
this._router.navigate([''])
return false;
}
and within the app-routing you place
const ACHEI_ROUTES: Routes = [
{
path:'',
component: LoginComponent,
},
{
path: 'home',
component: MenuLateralComponent,
canActivate: [AuthGuard]
},
Inside the app.module you have to declare as proof the guard
providers: [AuthService,AuthGuard],
and create an authentication service
import { Router } from '@angular/router';
import { Usuario } from './../../classes/usuario';
import { Injectable } from '@angular/core';
@Injectable()
export class AuthService {
constructor(private router: Router) { }
private usuarioAutenticado: boolean = false;
fazerLogin(usuario: Usuario) {
if (usuario.nome === 'login' &&
usuario.senha === 'senha') {
this.usuarioAutenticado = true
this.router.navigate(['home'])
} else {
this.usuarioAutenticado = false
};
}
getUsuarioAutenticado(){
return this.usuarioAutenticado
}
}