在angular5登录页面之前隐藏Navbar [英] hide Navbar before login page in angular5

查看:74
本文介绍了在angular5登录页面之前隐藏Navbar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在angular5应用程序中工作,因此我在github中使用了angular5模板,并且我尝试执行与本教程相同的操作,以在身份验证

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/

我没有收到任何错误,但是即使在对Users ..进行身份验证之后,导航栏也始终处于隐藏状态,我正在使用后端Spring Boot(Spring Security + JWT)

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 )

这是项目结构的样子:

app-sidebar-component.html文件:

The file 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 $是否为true,如果为true,导航栏将会显示.

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 .

使用文件_nav.ts的文件app-sidebar-nav.component.ts

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
  }



}

在src/app/views/pages/login.component.ts中

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

}

在目录服务中:

文件:auth.guard.ts

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

文件authentication.service.ts:

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

文件app.routing.ts

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

如您所见,我在本教程中添加的值canActivate:[AuthGuard]表示路径:"dashboard",

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

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

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

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

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?

编辑

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

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 :

在此文件中,我在"isLoggedIn $"下显示一条红线:未定义ng标识符isloggedIn $,组件声明,模板变量声明和元素引用不包含此类成员

推荐答案

您可以在(c1>)当前正在尝试使用它的组件中定义isLoggedIn$变量,也可以移动定义到的组件(app-sidebar-nav.component.ts),如下所示:

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

这篇关于在angular5登录页面之前隐藏Navbar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆