Tôi có một câu hỏi nhỏ liên quan đến bộ định tuyến Angular 2 sử dụng phiên bản 3.0.0-rc.1
Tôi muốn điều hướng đến thành phần nhà khác dựa trên vai trò người dùng như AdminComponent hoặc UserComponent. Bất cứ ai có thể xin giúp đỡ trong việc sửa đổi các tuyến đường dưới đây để tôi có thể đạt được các chức năng mong muốn?Góc 2 Điều hướng dựa trên vai trò trên cùng một đường dẫn
{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';
}
}
Cảm ơn.
cậu con số nó ra? – Dmitry
@Dmitry không may mắn nào – Ankush