Show Navbar after authenticating user in Angular

Asked

Viewed 331 times

0

I am trying to hide a Navbar and show only after I authenticate the user, I am using *ngIf and using an Eventemitter to return a bolean value, I initialized a variable called show Nu in my app.Component as false, however it is not receiving the value that comes from login.service that is, even after authenticating it is not appearing.

import { Injectable, EventEmitter } from '@angular/core';
import { Router } from "@angular/router";
import { Observable, BehaviorSubject } from 'rxjs';
import * as firebase from 'firebase/app';
import { AngularFireAuth } from '@angular/fire/auth';

@Injectable()
export class LoginService {

mostrarMenuEmitter = new EventEmitter<boolean>();

user: Observable<firebase.User>;
constructor(private router: Router, public afAuth: AngularFireAuth) {
    this.user = afAuth.authState;
}

public login(mail: string, password: string) {

    return new Promise((resolve, reject) => {

        this.afAuth.auth.signInWithEmailAndPassword(mail, password).then((user) => {

            localStorage['user'] = mail;
            this.mostrarMenuEmitter.emit(true);
            this.router.navigate(['/sistema/cliente']);
            console.log(user);


        })
            .catch((error) => {
                console.log(error);
                this.router.navigate(['/login']);

            });
    })
        .catch((error) => {
            console.log(error);
            this.router.navigate(['/login']);

        });
}

public logout() {
    return this.afAuth.auth.signOut();
}


}

import { OnInit, Component } from '@angular/core';
import { LoginService } from './login/login.service';
import { Observable } from 'rxjs';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'sistemang';

mostrarMenu: boolean = false;

constructor(private loginService: LoginService) {

}

ngOnInit() {
this.receberValor
}

receberValor(valor: boolean){

this.loginService.mostrarMenuEmitter.subscribe(
  valor => this.mostrarMenu = valor
)

}
}

<nav *ngIf="mostrarMenu" class="navbar navbar-expand-lg navbar-light bg-light">
<div class="collapse navbar-collapse" id="navbarNav">
  <ul class="navbar-nav">
    <li class="nav-item">
      <a class="nav-link" href="#" routerLink="/sistema/cliente" routerLinkActive="active">Cliente</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#" routerLink="/sistema/produto" routerLinkActive="active">Produto</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="#" routerLink="/sistema/carro" routerLinkActive="active">Carro</a>
      </li>
  </ul>
</div>

  • Welcome Eduardo to the site, please read our rules on how to ask a question, please post the code instead of images

  • Have you tried using a Subject behavior instead of an eventEmiiter?

  • Worst thing I ever tried

1 answer

0


Hi, I could do it here, the difference was I needed to create a component LoginComponent to use the EventEmitter, because the same allows communication between components. From what I saw in your code, you’re using it to communicate between a component and a service. I hope I can help you.

app.component.html

<nav *ngIf="mostrarMenu" class="navbar navbar-expand-lg navbar-light bg-light">
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" href="#" routerLink="/sistema/cliente" routerLinkActive="active">Cliente</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#" routerLink="/sistema/produto" routerLinkActive="active">Produto</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#" routerLink="/sistema/carro" routerLinkActive="active">Carro</a>
      </li>
    </ul>
  </div>
</nav>
<app-login-component (mostrarMenuEmitter)="receberMostraMenu($event)"></app-login-component>


<router-outlet></router-outlet>

login-Component.html

<p>
  login-component works!
  <button (click)="login()">{{nomeBotao}}</button>

</p>

app.componentts.

export class AppComponent {

  public mostrarMenu = false;


  receberMostraMenu(mostraMenuLogin) {
    console.log('mostraMenuLogin', mostraMenuLogin);
    this.mostrarMenu = mostraMenuLogin;
  }
}

login-Component.component.html

@Component({
  selector: 'app-login-component',
  templateUrl: './login-component.component.html',
  styleUrls: ['./login-component.component.css']
})
export class LoginComponentComponent implements OnInit {

  @Output() mostrarMenuEmitter = new EventEmitter();

  private mail: string;
  private password: string;
  public nomeBotao: string = 'Logar';

  constructor(private loginService: LoginServiceService) {

  }

  ngOnInit() {}

  public login() {
    const mostrarMenu = this.loginService.login(this.mail, this.password);
    this.nomeBotao = mostrarMenu ? 'Deslogar' : 'Logar';
    this.mostrarMenuEmitter.emit(mostrarMenu);
  }



}

login-service.ts

@Injectable({
  providedIn: 'root'
})
export class LoginServiceService {

  logado = false;

  constructor() {}

  public login(mail: string, password: string): boolean {
    this.logado = !this.logado;
    return this.logado;
  }
}
  • I did not understand very well, I put a method called receiv allor, but I think it is not correct the way I did.

Browser other questions tagged

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