Sruthish
Sruthish

Reputation: 53

Angular Hide Navbar Menu from Login page

I have implemented a nav bar show/hide for login/logout for user in my angular 5 app, this is my reference

https://loiane.com/2017/08/angular-hide-navbar-login-page/

this works fine in my local, but fails when deployed. what could be the issue. I'm using the code as it is with minor changes.

Auth Gard

canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): 
Observable<boolean> {

    return this.authService.isLoggedIn.pipe(
        take(1),
        map((isLoggedIn: boolean) => {
          if (!isLoggedIn) {
           this.router.navigate(['/login']);
           return false;
          }
          return true;
        })
      );

  }

Auth service

  private loggedIn: BehaviorSubject<boolean> = new 
BehaviorSubject<boolean>(false);

  get isLoggedIn() {
    this.login();
    return this.loggedIn.asObservable();
  }

  constructor(private router: Router, private sessionService: 
SessionService) {}

  login() {
    const userSession = this.sessionService.get('userEmail');
    this.loggedIn.next(userSession !== null ? true : false);
  }

  logout() {
    this.loggedIn.next(false);
    this.router.navigate(['/login']);
  }

Header Component

isLoggedIn$: Observable<boolean>;
  userImage: string;

  constructor(private sessionService: SessionService, private authService: 
AuthService, private route: ActivatedRoute) {
    this.route.params.subscribe(val => {
      this.isLoggedIn$ = this.authService.isLoggedIn;
   });
  }

  ngOnInit() {

    this.isLoggedIn$ = this.authService.isLoggedIn;
    const img = this.sessionService.get('userImage');
    this.userImage = img === null ? '' : <string>img;

  }

  toggleMenu() {
    this.showMenu = !this.showMenu;
    console.log(this.showMenu);
  }

Header Html

<ul class="header_main_nav condensed" *ngIf="isLoggedIn$.source._value">
      <li class="routlink">
        <a [routerLink]="['/agileBomRefLnk']" routerLinkActive="active">
          <span class="glyphicon glyphicon-search"></span>
          <span class="link-text">Agile BOM</span>
        </a>
      </li>
</ul>

Upvotes: 1

Views: 9040

Answers (1)

Rabea AlTaradeh
Rabea AlTaradeh

Reputation: 224

In a simple way, with minimum changes

    merge login component with AppComponent  and put *ngIf on 
    <div *ngIf="!loginPage">
     <app-header [(loginbutton)]="loginPage"></app-header><!-- [(loginbutton)] is an output to trigger the boolean "loginPage" -->

     <router-outlet></router-outlet>
</div>
 <div *ngIf="!loginPage">
LoginCode...
</div>

I hope to be that helpful for you ...

Upvotes: 0

Related Questions