在angular5的登录页面之前隐藏导航栏

hide Navbar before login page in angular5

我在 angular5 应用程序中工作,所以我在 github 中使用了一个 angular5 模板,并且我尝试按照本教程的方法在身份验证之前隐藏导航栏 https://loiane.com/2017/08/angular-hide-navbar-login-page/

我没有收到任何错误,但即使在用户身份验证后导航栏也始终隐藏..,我正在使用后端 spring 引导(spring 安全 + JWT)

项目结构如下:

文件 app-sidebar-component.html :

在这个文件中,我在 "isLoggedIn$" 下得到一条红线,上面写着:未定义 ng 标识符 isloggedIn$,组件声明、模板变量声明和元素引用不包含此类会员

 <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>

如您所见,我正在使用条件 ngIf 来测试变量 isLoggedIn$ 是否为真,如果为真,导航栏将显示。

使用文件 _nav.ts

的文件 app-sidebar-nav.component.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
  }



}

在 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;
        })
  }

}

在目录服务中:

文件: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;
      });
  }
}

文件 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');
  }

文件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 {}

如您所见,我已经在教程中添加了值 canActivate: [AuthGuard] 路径:'dashboard',

这是登录前应该隐藏的文件_nav.ts,它是包含在上面的 app-sidebar-nav.component.ts 中的文件。

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'
      }
    ]
  }
];

当我在身份验证后检查 isLoggedIn$ 的值时,我得到 'true' 但文件 _nav.ts 的导航栏始终隐藏。任何的想法?

编辑

文件:appSidebar.component.ts:这个文件是空的,因为开发这个模板的人使用文件 app-sidebar-nav.component.ts 而不是 appSidebar.component.ts 来显示导航栏,这就是我在 app-sidebar-nav.component.ts 中声明变量 îsLoggedIn$ 的原因,因为它在代码中。 但我得到了一个警告:它说:

在这个文件中,我在 "isLoggedIn$" 下得到一条红线,上面写着:未定义 ng 标识符 isloggedIn$,组件声明、模板变量声明和元素引用不包含此类会员

您可以在您当前尝试在 (app-sidebar-component.ts) 中使用它的组件中定义 isLoggedIn$ 变量,或者您可以将 *ngIf 移动到您所在的组件像这样定义 (app-sidebar-nav.component.ts):

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>;
  ...
}