Angle 7中基于角色的导航

时间:2019-03-05 06:48:09

标签: navigation angular2-routing angular7

全部,我担任三个角色,例如管理员,用户,主持人。我正在尝试,如果主持人登录,他将重定向到主持人页面,如果管理员登录,他将重定向到管理页面。在我的导航栏中,我试图根据角色用户登录名隐藏/显示导航链接。我尝试了不同的方法。谁能给我建议解决方案?

这是我的导航:

<nav class="navbar">
    <div class="navbar-header">
      <a href="/"><img src="favicon.ico" alt="Angular" class="logo"></a>
    </div>
    <ul class="navbar-pill">
      <ng-template [ngIf]="!userService.isLoggedIn()">
        <li routerLinkActive="active">
          <a routerLink="/signup">Sign up</a>
        </li>
        <li routerLinkActive="active">
            <a routerLink="/login">Login</a>
        </li>
      </ng-template>

      <li routerLinkActive="active" *ngIf="userService.isLoggedIn()">
        <a routerLink="/askquestion">Ask Question</a>
      </li>

      <li routerLinkActive="active" *ngIf="userService.isLoggedIn()">
        <a routerLink="/userslist">User List</a>
      </li>

      <li routerLinkActive="active" *ngIf="userService.isLoggedIn()">
            <a href="#" (click)="onLogout()">Logout</a>
          </li>


      </ul>
  </nav>

<router-outlet></router-outlet>

我的导航文件

import { Component } from '@angular/core';
import { UserService } from './shared/user.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'cform';
constructor(private userService: UserService, private router: Router){}

onLogout(){
  this.userService.deleteToken();
  this.router.navigate(['/login']);
}
}

路由模块:

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

import { UserComponent } from './user/user.component';
import { SignUpComponent } from './user/sign-up/sign-up.component';
import { SignInComponent } from './user/sign-in/sign-in.component';
import { AuthGuard } from './auth/auth.guard';
import { QuestionsComponent } from './questions/questions.component';
import { UserlistComponent } from './userlist/userlist.component';


const routes: Routes = [
  { path: '', pathMatch: 'full', redirectTo: 'login' },
  { path: 'signup', component: UserComponent,
    children: [{ path: '', component: SignUpComponent }]   },
  { path: 'login', component: UserComponent,
    children: [{ path: '', component: SignInComponent }] },
  { path: 'userslist', component: UserlistComponent, canActivate: [AuthGuard], data: { roles: ['admin'] } },
  { path: 'askquestion', component: QuestionsComponent, canActivate: [AuthGuard], data: { roles: ['moderator'] } }   
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { 
  static components = [UserComponent, SignUpComponent, SignInComponent, QuestionsComponent, UserlistComponent];
 }

0 个答案:

没有答案