Angular 2基于角色的相同路径导航
Angular 2 Role based navigation on same path
我有一个关于使用版本3.0.0-rc.1
的Angular 2路由器的小问题,我想根据用户角色(如AdminComponent或UserComponent)导航到不同的主组件。谁能帮忙修改下面的路线,使我能实现所需的功能?
{path: 'login', component: LoginComponent}, // <--- This redirects to '/' in case user is logged in
{
path: '',
component: HomeComponent,
canActivate: [AuthGuardService], // <--- Check if user is logged in, else redirect to login
children: [
{
path: '',
component: AdminComponent // <--- Want to navigate here if user role is 'admin'
},
{
path: '',
component: UserComponent // <--- Want to navigate here if user role is 'user'
}
]
}
AuthGuardService.ts
import {Injectable} from "@angular/core";
import {CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot} from "@angular/router";
import {AuthService} from "./auth.service";
@Injectable()
export class AuthGuardService implements CanActivate {
constructor(private authService: AuthService, private router: Router) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.authService.isLoggedIn()) {
return true;
}
// Store the attempted URL for redirecting
this.authService.redirectUrl = state.url;
// Navigate to the login page with extras
this.router.navigate(['/login']);
return false;
}
}
AuthService.ts
import {Injectable} from "@angular/core";
@Injectable()
export class AuthService {
redirectUrl: string;
logout() {
localStorage.clear();
}
isLoggedIn() {
return localStorage.getItem('token') !== null;
}
isAdmin() {
return localStorage.getItem('role') === 'admin';
}
}
谢谢。
您可以通过以下方式实现。
{path: 'login', component: LoginComponent}, // <--- This redirects to '/' in case user is logged in
{
path: '',
component: HomeComponent,
canActivate: [AuthGuardService],
}
这是你的主组件html(home.component.html)
<app-admin *ngIf="user_role==='admin'"></app-admin>
<app-user *ngIf="user_role==='user'"></app-user>
确保你在home组件的typescript文件中分配了user_role
这是你的管理组件html(admin.component.html)
<div>
this is admin component
</div>
这是你的用户组件html(user.component.html)
<div>
this is user component
</div>
希望,这将帮助你。
问题是你不能有两个路径相同的路由。您可以做的最简单的更改是将路径更改为如下内容:
{
path: 'admin',
component: AdminComponent
},
{
path: 'user',
component: UserComponent
}
这可能是最好的选择,因为您希望组件根据用户角色而不同。您可能还希望其他组件有所不同,您可以通过向admin或user路由添加子路由来轻松实现这一目标。
在你的AuthGuard中,你仍然只返回true,但是你为admin和user路由设置了另外两个保护。它检查用户是否是管理员。
登录后通过检查用户角色重定向到正确的路由然后在组件中执行router.navigate(['/admin'])
或router.navigate(['/user'])
相关文章:
- 单击顶部导航时如何进行向下滚动效果(向下滑动).
- angular 1.5应用程序中的导航栏
- Javascript:使用绝对路径设置img src
- 无法从jquery Mobile导航栏重定向到另一个页面
- 如何在d3.js中返回路径的y坐标
- 复制图像路径以单击它
- 引导程序:在导航栏中,显示悬停在单个位置的基于Li Link的不同内容
- Jquery-如何将活动类添加到整个导航菜单路径中
- WebBrowser DocumentText 无法在不提供完整路径的情况下导航 javascript
- 跟踪 URL 中的 Div 导航路径
- URI 路径导航问题
- 使用 redux-simple-router 导航到另一条路径
- 如何在使用javascript或Jquery导航到其他页面时替换路径
- 粘性导航使用路径点调整大小的问题
- 谷歌地图路线方向路径颜色改变导航仪从一个航路点移动到另一个航路点
- jQuery路径点粘性导航,当通过点击向上滚动是1px off
- 创建合适的导航路径
- Angular 2基于角色的相同路径导航
- jQuery路径点导航条
- 基于URL路径的Javascript/jQuery导航