关于使用版本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: 'admin',
component: AdminComponent
},
{
path: 'user',
component: UserComponent
}
这可能是最佳选择,因为您希望根据用户角色使组件不同。您可能还希望其他组件不同,您可以通过将子项添加到管理员或用户路由来轻松完成。
在您的AuthGuard中,您仍然只返回true,但是您为管理员和用户路由制作了另外两个警卫。检查用户是否是管理员。
然后通过检查用户角色重定向到正确的路径,然后在组件中执行router.navigate(['/admin'])
或router.navigate(['/user'])