我的路由模块中定义了主页的网站为:
const appRoutes: Routes = [
{
path: '',
component: HomeComponent
}];
现在我想为管理员用户显示一个不同的主页(一个仪表板页面)。 我可以更改"组件"根据用户的角色调用?
伪代码中的类似于:
const appRoutes: Routes = [
{
path: '',
IF UserRole = 'Admin'
component: DashboardComponent
ELSE
component: HomeComponent
}];
答案 0 :(得分:2)
@ andrea06590答案中的教程链接非常简要地概述了基于身份验证和授权的路由。
简而言之,某人可以使用以下方式:
app.routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
{ path : '' , redirectTo : '', pathMatch: 'full' , canActivate : [ RedirectGuardService ] },
{ path : 'admin' , component : AdminComponent , canActivate : [AuthGuardService] , data : { role : 'admin'}},
{ path : 'user' , component : UserComponent , canActivate : [AuthGuardService] , data : { role : 'user'}}
{ path : '**' , component : NotFoundComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
auth-guard.service.ts
import { Injectable } from '@angular/core';
import { Router , CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from '../auth-service/auth-service.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuardService implements CanActivate {
constructor(
private router: Router,
private authService: AuthService
) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : Observable<boolean> | Promise<boolean> | boolean {
const currentUser = this.authService.userVal; // Getting User Value by decoding JWT Token
const role = route.data.role; // Getting role value which we passed to data object in router configuration
if (currentUser) {
if(role && role.indexOf(currentUser.role) > -1)
return true;
else
return false;
}
return false;
}
}
redirect-guard.service.ts
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from '../auth-service/auth-service.service';
import { Observable } from 'rxjs';
import { IUser } from 'client/app/interfaces';
@Injectable({
providedIn: 'root'
})
export class RedirectGuardService implements CanActivate {
constructor(
private router: Router,
private authService: AuthService
) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : Observable<boolean> | Promise<boolean> | boolean {
const user = <IUser>this.authService.userVal;
if (user && user['user']) {
this.router.navigate(['/'+ user['user'].role]);
return true;
}
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
}
}
答案 1 :(得分:0)
你一定会在这个页面找到你需要的东西:
https://angular.io/guide/router
但作为一个快速而肮脏的答案,您只需检查用户是否是HomeComponent中的管理员,如果是,则重定向他。
答案 2 :(得分:0)
要做到这一点,有一种叫做Angular Guards Route https://medium.com/@ryanchenkie_40935/angular-authentication-using-route-guards-bf7a4ca13ae3
的东西