如何使用Angular有选择地隐藏导航栏?

时间:2016-11-11 09:09:48

标签: angular navigation navigationbar

我们想隐藏login页面上的登录栏。模板中的值永远不会更改,我们要隐藏导航的唯一页面位于登录页面上。

启用或禁用导航栏时调用的服务。 isAuthenticated.service:

import {Injectable} from '@angular/core';
import {Observable}     from 'rxjs/Observable';

@Injectable()
export class isAuthenticatedService{

userLoggedIn : boolean = false;

//call this function when login status changes
changeLoginStatus(status: boolean){
    this.userLoggedIn = status;
    console.log("in changeLoginStatus: ", status);
}

getLoginStatus(){
    return this.userLoggedIn;
}
}

app.component:

import {Component} from '@angular/core';
import {ProfilComponent} from './profil.component';
import {EditProfilComponent} from './editProfil.component';
import { HTTPService } from './http.service';
import {CookieService} from 'angular2-cookie/services/cookies.service';
import {Router} from '@angular/router';
import {isAuthenticatedService} from './isAuthenticated.service'

@Component({
selector: 'my-app',
templateUrl: './app/main.html',
providers: [HTTPService, CookieService, isAuthenticatedService]
})
export class AppComponent{
constructor(private _httpService: HTTPService, private _cookieService: CookieService, public router: Router, private _isAuthenticatedService: isAuthenticatedService){
    console.log(this.router.url);
}
};

app.component中用于显示导航的模板。

main.html中:

<div [hidden]="_isAuthenticatedService.userLoggedIn">
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="collapse navbar-collapse">
  <ul class="nav navbar-nav">
    <li><a routerLink="/mainpage">Portal |</a></li>
   <li><a routerLink="/profil">Profil</a></li>
    <li><a href="/">Unternehmen</a></li>
  </ul>
  <ul class="nav navbar-nav navbar-right">
 <div class="dropdown" style="float:right;">
<button class="dropdown-toggle btn btn-primary" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false" id ="profildd">Profil <span class="caret"></span></button>
    <ul class="dropdown-menu">
    <li><a routerLink="/profil" routerLinkActive="active">Verwalten</a></li>
    <li role="separator" class="divider"></li>
    <li><a routerLink="/download" routerLinkActive="active">Organisation</a></li>
    <li role="separator" class="divider"></li>
    <li><a routerLink="/" (click)="logout()">Logout</a></li>
    </ul> 
</div>
</ul>
</div>
</div>

   

如果登录成功,则从登录组件调用函数'changeLoginStatus(boolean)'。

修改1:更改了提供商

将提供商从app.component移至app.module.ts

app.module.ts:

@NgModule({
imports: [ 
BrowserModule,
HttpModule,
FormsModule,
RouterModule.forRoot([
  {path : '', component: LoginComponent},
  {path: 'mainpage', component: MainPageComponent},
  {path: 'profil', component: ProfilComponent},
  {path: 'editProfil', component: EditProfilComponent},
  {path: 'login', component: LoginComponent}
])

],

 declarations: [ AppComponent, ProfilComponent, EditProfilComponent, LoginComponent, MainPageComponent],
 providers : [
{       provide: XSRFStrategy,
        useValue: new CookieXSRFStrategy('XSRF-Token', 'XSRF-TOKEN')
}, isAuthenticatedService, CookieService, HTTPService],
bootstrap:    [ AppComponent ]

})
export class AppModule { }

2 个答案:

答案 0 :(得分:2)

问题是

providers: [HTTPService, CookieService, isAuthenticatedService]

此行创建不同的服务实例(每个组件),因此您不会有预期的结果。

您应该使用单一服务,该服务在组件中共享服务的单个实例,其中一个组件在服务中更改某些内容,而其他组件通过服务获得相同的更新

因此,您应该在RootModule'sAppModule's @NgModule decorator中声明您的服务,如下所示,

@NgModule({
   ...
   providers: [HTTPService, CookieService, isAuthenticatedService]  
   //<<< this will create single instance of services throughout app
  ...
})

providers:[...]

删除@Component声明
@Component({
    selector: 'my-app',
    templateUrl: './app/main.html',
    providers: [HTTPService, CookieService, isAuthenticatedService] 
    //<<< providers not required here as it creates different instance per component.

})  

编辑1:

试试这个,

<div [hidden]="_isAuthenticatedService.getLoginStatus()">

答案 1 :(得分:0)

只是想知道为什么这里有如此复杂的解决方案?您只需要检查用户是否已在导航组件中登录,如下所示:

<强> Navmenu.component.ts:

import { Component } from '@angular/core';
import {Location, LocationStrategy, PathLocationStrategy} from '@angular/common';
import { AuthService } from '../authguard/auth.service';

@Component({
selector: 'nav-menu',
providers: [Location, { provide: LocationStrategy, useClass: PathLocationStrategy }],
templateUrl: './navmenu.component.html',
styleUrls: ['./navmenu.component.css']})

export class NavMenuComponent {
  constructor(private authService: AuthService) { }
  location: Location;
  isActive() {
  return !this.authService.loggedIn();
  }
...
}

<强> navmenu.component.html:

<div class='main-nav' [hidden]="isActive()">
<div class='navbar navbar-inverse'>
...

然后,在您的顶部菜单栏中,有一个登录/注销'面板':

 <ul class="nav navbar-nav navbar-right">
        <li>
            <a (click)=authService.login() *ngIf="!authService.loggedIn()">Log In</a>
        </li>
        <li>
            <a (click)=authService.logout() *ngIf="authService.loggedIn()">Log Out</a>
        </li>
    </ul>
</nav>
<div class='row'>
    <div class='col-sm-3'>
        <nav-menu></nav-menu>
...