首页 文章

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

提问于
浏览
0

我'm working in angular5 app , so i'在github中使用了angular5模板,我试着像本教程一样在认证前隐藏导航栏https://loiane.com/2017/08/angular-hide-navbar-login-page/

我没有得到任何错误,但导航栏总是隐藏,即使在用户身份验证后...,我正在使用后端 spring 启动( spring 安全JWT)

这就是项目结构的样子:

enter image description here

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

如您所见,我正在使用条件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的导航栏总是被隐藏 . 任何的想法?

EDIT

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

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

enter image description here

1 回答

  • 0

    您可以在当前尝试使用它的组件中定义 isLoggedIn$ 变量( app-sidebar-component.ts ),也可以将 *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>;
      ...
    }
    

相关问题