关于使用版本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';
}
}
感谢。
答案 0 :(得分:2)
您可以通过以下方式实现。
{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>
这是您的管理组件html(admin.component.html)
<div>
this is admin component
</div>
这是您的用户组件html(user.component.html)
<div>
this is user component
</div>
希望,这会为您提供帮助。
答案 1 :(得分:-1)
问题是你不能有两条路径相同的路线。您可以做出的最简单的更改是将路径更改为以下内容:
{
path: 'admin',
component: AdminComponent
},
{
path: 'user',
component: UserComponent
}
这可能是最佳选择,因为您希望根据用户角色使组件不同。您可能还希望其他组件不同,您可以通过将子项添加到管理员或用户路由来轻松完成。
在您的AuthGuard中,您仍然只返回true,但是您为管理员和用户路由制作了另外两个警卫。检查用户是否是管理员。
您可以通过检查用户角色,然后在您执行的router.navigate(['/admin'])
或router.navigate(['/user'])