The best way to make it and with routes and routes guard there would be so in the guard of routes you place
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 Voce app-routing
const ACHEI_ROUTES: Routes = [
{
path:'',
component: LoginComponent,
},
{
path: 'home',
component: MenuLateralComponent,
canActivate: [AuthGuard]
},
Inside the.module Voce app you have to declare the guard as provaider
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
}
}
It logs in without updating the page?
– Sam
Life cycle maybe? Depending on your user model(?) you can check if there has been a change in the
ngOnChange
– fsi