hide Navbar before login page in angular5

2019-09-02 11:01发布

问题:

i'm working in angular5 app , so i've used an angular5 template in github , and i tried to do the same as this tutorial to hide the navigation bar before authentication https://loiane.com/2017/08/angular-hide-navbar-login-page/

I don't get any errors but the nav bar is always hidden even after the authentication of Users .. , i'm working with backend spring boot (spring security + JWT )

this is how the project structure looks like :

The file app-sidebar-component.html :

in this file i get a red line under the "isLoggedIn$" it says : ng identifier isloggedIn$ is not defined , the component declaration , template variable declaration and elements references do not contain such a member

 <div class="sidebar">
  <app-sidebar-header></app-sidebar-header>
  <app-sidebar-form></app-sidebar-form>
  <app-sidebar-nav *ngIf="isLoggedIn$ | async"></app-sidebar-nav>
  <app-sidebar-footer></app-sidebar-footer>
  <app-sidebar-minimizer></app-sidebar-minimizer>
</div>

As you see i'm using a condition ngIf to test if the variable isLoggedIn$ is true , if it's true the nav bar will show up .

the file app-sidebar-nav.component.ts that uses the file _nav.ts

   import { Component, ElementRef, Input, OnInit, Renderer2 } from '@angular/core';
import {AuthenticationService} from '../../../service/authentication.service';

// Import navigation elements
import { navigation } from './../../_nav';
@Component({
  selector: 'app-sidebar-nav',
  template: `
    <nav class="sidebar-nav">
      <ul class="nav">
        <ng-template ngFor let-navitem [ngForOf]="navigation">
          <li *ngIf="isDivider(navitem)" class="nav-divider"></li>
          <ng-template [ngIf]="isTitle(navitem)">
            <app-sidebar-nav-title [title]='navitem'></app-sidebar-nav-title>
          </ng-template>
          <ng-template [ngIf]="!isDivider(navitem)&&!isTitle(navitem)">
            <app-sidebar-nav-item [item]='navitem'></app-sidebar-nav-item>
          </ng-template>
        </ng-template>
      </ul>
    </nav>`
})
export class AppSidebarNavComponent implements OnInit {

  public navigation = navigation ;

  isLoggedIn$: Observable<boolean>;

  constructor(private authService:AuthenticationService) {

  }

  ngOnInit() {

    this.isLoggedIn$ = this.authService.isLoggedIn;
  }


  public isDivider(item) {
    return item.divider ? true : false
  }

  public isTitle(item) {
    return item.title ? true : false
  }



}

in src/app/views/pages/login.component.ts

import { Component } from '@angular/core';
import {AuthenticationService} from '../../../service/authentication.service';
import {Router} from '@angular/router';

@Component({
  templateUrl: 'login.component.html'
})
export class LoginComponent {

  mode:number=0;

  constructor(private router:Router , private authService:AuthenticationService) { }


  onLogin(user){
    this.authService.login(user)
      .subscribe(resp=>{
          let jwt = resp.headers.get('Authorization');
           this.authService.saveToken(jwt);
           this.authService.setLoggedInt();
           this.router.navigateByUrl('/dashboard');

        },
        err=>{
          this.mode=1;
        })
  }

}

In directory service :

File : auth.guard.ts

import { Injectable } from '@angular/core';
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  Router
} from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/take';
import 'rxjs/add/operator/map';
import {AuthenticationService} from './authentication.service';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private authService: AuthenticationService,
    private router: Router
  ) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> {
    return this.authService.isLoggedIn
      .take(1)
      .map((isLoggedIn: boolean) => {
        if (!isLoggedIn){
          this.router.navigate(['pages']);
          return false;
        }
        return true;
      });
  }
}

The file authentication.service.ts :

import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {JwtHelper} from 'angular2-jwt';
import {Observable} from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';


@Injectable()
export class AuthenticationService{

  private host:string="http://localhost:8080";
  private jwtToken=null ;
  private roles:Array<any>;
  private user:string;
  private loggedIn = new BehaviorSubject<boolean>(this.tokenAvailable());

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

  private tokenAvailable(): boolean {
    console.log(localStorage.getItem('token'));
    return !!localStorage.getItem('token');
  }

  constructor(private http:HttpClient){

  }
  login(user){

    return this.http.post(this.host+"/login",user,{observe: 'response'});

  }

  getToken(){
    return this.jwtToken;
  }

  setLoggedInt(){
    this.loggedIn.next(true);

  }

  loadToken(){
    this.jwtToken=localStorage.getItem('token');
  }

The file app.routing.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

// Import Containers
import {
  FullLayoutComponent,
  SimpleLayoutComponent
} from './containers';
import {AuthGuard} from '../service/auth.guard';

export const routes: Routes = [
  {
    path: '',
    redirectTo: 'pages',
    pathMatch: 'full',
  },
  {
    path: '',
    component: FullLayoutComponent,
    data: {
      title: 'Home'
    },
    children: [
      {
        path: 'GestionClients',
        loadChildren: './views/Admin/GestionClients/client.module#ClientModule'
      },
      {
        path: 'GestionDevloppeurs',
        loadChildren: './views/Admin/GestionDevloppeurs/devloppeur.module#DevloppeurModule'
      },
      {
        path: 'GestionProject',
        loadChildren: './views/Admin/GestionProjects/projet.module#ProjetModule'
      },
      {
        path: 'base',
        loadChildren: './views/base/base.module#BaseModule'
      },
      {
        path: 'buttons',
        loadChildren: './views/buttons/buttons.module#ButtonsModule'
      },
      {
        path: 'dashboard',
        canActivate: [AuthGuard],
        loadChildren: './views/dashboard/dashboard.module#DashboardModule'
      },
      {
        path: 'icons',
        loadChildren: './views/icons/icons.module#IconsModule'
      },
      {
        path: 'notifications',
        loadChildren: './views/notifications/notifications.module#NotificationsModule'
      },
      {
        path: 'theme',
        loadChildren: './views/theme/theme.module#ThemeModule'
      },
      {
        path: 'widgets',
        loadChildren: './views/widgets/widgets.module#WidgetsModule'
      }
    ]
  },
  {
    path: 'pages',
    component: SimpleLayoutComponent,
    data: {
      title: 'Pages'
    },
    children: [
      {
        path: '',
        loadChildren: './views/pages/pages.module#PagesModule',
      }
    ]
  }
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

As you can see i've added as in the tutorial the value canActivate: [AuthGuard] for the path: 'dashboard',

and this is the file _nav.ts that should be hidden before login , and it's the one included in app-sidebar-nav.component.ts above.

export const navigation = [
  {
    name: 'Tableau de bord',
    url: '/dashboard',
    icon: 'icon-speedometer',
  },
  {
    name: 'Clients',
    url: '/GestionClients',
    icon: 'icon-puzzle',
    children: [
      {
        name: 'Liste des clients',
        url: '/GestionClients/list',
        icon: 'icon-puzzle'
      },
      {
        name: 'Ajouter un client',
        url: '/GestionClients/ajouter',
        icon: 'icon-puzzle'
      }
      ]
  },
  {
    name: 'Développeurs',
    url: '/GestionDevloppeurs',
    icon: 'icon-puzzle',
    children: [
      {
        name: 'Liste des développeurs',
        url: '/GestionDevloppeurs/list',
        icon: 'icon-puzzle'
      },
      {
        name: 'Ajouter un nouveau développeur',
        url: '/GestionDevloppeurs/ajouter',
        icon: 'icon-puzzle'
      }
    ]
  },
  {
    name: 'Projets',
    url: '/GestionProject',
    icon: 'icon-puzzle',
    children: [
      {
        name: 'Liste des projets',
        url: '/GestionProject/list',
        icon: 'icon-puzzle'
      },
      {
        name: 'Ajouter un projet',
        url: '/GestionProject/ajouter',
        icon: 'icon-puzzle'
      }

    ]
  },
  {
    name: 'Base',
    url: '/base',
    icon: 'icon-puzzle',
    children: [
      {
        name: 'Cards',
        url: '/base/cards',
        icon: 'icon-puzzle'
      },
      {
        name: 'Carousels',
        url: '/base/carousels',
        icon: 'icon-puzzle'
      },
      {
        name: 'Collapses',
        url: '/base/collapses',
        icon: 'icon-puzzle'
      },
      {
        name: 'Forms',
        url: '/base/forms',
        icon: 'icon-puzzle'
      },
      {
        name: 'Pagination',
        url: '/base/paginations',
        icon: 'icon-puzzle'
      },
      {
        name: 'Popovers',
        url: '/base/popovers',
        icon: 'icon-puzzle'
      },
      {
        name: 'Progress',
        url: '/base/progress',
        icon: 'icon-puzzle'
      },
      {
        name: 'Switches',
        url: '/base/switches',
        icon: 'icon-puzzle'
      },
      {
        name: 'Tables',
        url: '/base/tables',
        icon: 'icon-puzzle'
      },
      {
        name: 'Tabs',
        url: '/base/tabs',
        icon: 'icon-puzzle'
      },
      {
        name: 'Tooltips',
        url: '/base/tooltips',
        icon: 'icon-puzzle'
      }
    ]
  },
  {
    name: 'Buttons',
    url: '/buttons',
    icon: 'icon-cursor',
    children: [
      {
        name: 'Buttons',
        url: '/buttons/buttons',
        icon: 'icon-cursor'
      },
      {
        name: 'Dropdowns',
        url: '/buttons/dropdowns',
        icon: 'icon-cursor'
      },
      {
        name: 'Social Buttons',
        url: '/buttons/social-buttons',
        icon: 'icon-cursor'
      }
    ]
  },

  {
    name: 'Icons',
    url: '/icons',
    icon: 'icon-star',
    children: [
      {
        name: 'Flags',
        url: '/icons/flags',
        icon: 'icon-star',
        badge: {
          variant: 'success',
          text: 'NEW'
        }
      },
      {
        name: 'Font Awesome',
        url: '/icons/font-awesome',
        icon: 'icon-star',
        badge: {
          variant: 'secondary',
          text: '4.7'
        }
      },
      {
        name: 'Simple Line Icons',
        url: '/icons/simple-line-icons',
        icon: 'icon-star'
      }
    ]
  },
  {
    name: 'Notifications',
    url: '/notifications',
    icon: 'icon-bell',
    children: [
      {
        name: 'Alerts',
        url: '/notifications/alerts',
        icon: 'icon-bell'
      },
      {
        name: 'Modals',
        url: '/notifications/modals',
        icon: 'icon-bell'
      }
    ]
  },
  {
    name: 'Widgets',
    url: '/widgets',
    icon: 'icon-calculator',
    badge: {
      variant: 'info',
      text: 'NEW'
    }
  },
  {
    divider: true
  },
  {
    title: true,
    name: 'Extras',
  },
  {
    name: 'Pages',
    url: '/pages',
    icon: 'icon-star',
    children: [
      {
        name: 'Login',
        url: '/pages/login',
        icon: 'icon-star'
      },
      {
        name: 'Register',
        url: '/pages/register',
        icon: 'icon-star'
      },
      {
        name: 'Error 404',
        url: '/pages/404',
        icon: 'icon-star'
      },
      {
        name: 'Error 500',
        url: '/pages/500',
        icon: 'icon-star'
      }
    ]
  }
];

when i check the value of isLoggedIn$ after authentication i get 'true' but the nav bar of the file _nav.ts is always hidden . Any idea?

EDIT

File : appSidebar.component.ts : this file is empty , because the man who devlopped this template has used the file app-sidebar-nav.component.ts instead of appSidebar.component.ts to show the navigation bar , that's why i declared the variable îsLoggedIn$ in app-sidebar-nav.component.ts as it's in the code . but i get like a warning : it says :

in this file i get a red line under the "isLoggedIn$" it says : ng identifier isloggedIn$ is not defined , the component declaration , template variable declaration and elements references do not contain such a member

回答1:

You can either define the isLoggedIn$ variable in the component that you are currently trying to use it in (app-sidebar-component.ts) or you can move the *ngIf to the component where you have it defined (app-sidebar-nav.component.ts) like so:

app-sidebar-component.html

<div class="sidebar">
  <app-sidebar-header></app-sidebar-header>
  <app-sidebar-form></app-sidebar-form>
  <app-sidebar-nav></app-sidebar-nav>
  <app-sidebar-footer></app-sidebar-footer>
  <app-sidebar-minimizer></app-sidebar-minimizer>
</div>

app-sidebar-nav.component.ts

@Component({
  selector: 'app-sidebar-nav',
  template: `
    <nav class="sidebar-nav" *ngIf="isLoggedIn$ | async">
        ...
    </nav>`
})
export class AppSidebarNavComponent implements OnInit {
  isLoggedIn$: Observable<boolean>;
  ...
}