Update Angular Component 4?

Asked

Viewed 900 times

0

Good morning!

In short, I have a Navbar component and it has an if that if you are logged in appears some items and if you are not, others appear. It works, the problem is that to validate the change, I need to give him an F5 to call the "IF" again. So, is there any way that I could correct that and automatically make that change? Thank you :D

  • It logs in without updating the page?

  • Life cycle maybe? Depending on your user model(?) you can check if there has been a change in the ngOnChange

1 answer

1


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
  }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.