我创建了一个路线保护员,阅读了一些博客和Angular 2官方文档。它适用于非参数路由,但在参数化路由中不起作用。
代码示例,
const routes: Routes = [
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [AuthGuard],
children: [
{ path: 'Customers', component: HomeComponent },
{ path: 'CustomerProfile/:id', component: DriverProfileComponent },
{ path: '', redirectTo: 'Customers', pathMatch: 'full' },
]
}
];
AUTH-guard.service.ts
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { LocalStorageService } from 'angular-2-local-storage';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private _router: Router,
private _localStorage: LocalStorageService,
) { }
menus: any = {
dashboard: [
'/dashboard/Customers',
'/dashboard/CustomerProfile'
],
driver: [],
client: [
'/client/account-setup'
]
};
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
let url: string = state.url;
let menus: string[] = this.menus[this._localStorage.get('type') + ''];
console.log(state.url); /* /dashboard/ClientProfile/1 */
if (menus.indexOf(url) != -1) {
return true;
}
return false;
}
}