我想根据角色限制路线。我想在我的canActivate方法中检查导航路径是否有权访问页面。但是,this.router.url
这给了我以前的路线而不是当前的导航路线。
答案 0 :(得分:2)
使用route: ActivatedRouteSnapshot
可以解决您的问题:
canActivate(route: ActivatedRouteSnapshot) {
console.log(route.url);
...
}
您可以在此处查看ActivatedRouteSnapshot对象的完整规范:
https://angular.io/docs/ts/latest/api/router/index/ActivatedRouteSnapshot-interface.html
答案 1 :(得分:1)
您可能有兴趣从此RouterStateSnapshot
方法版本的canActivate
参数中获取网址以获取完整路径(使用Angular 5进行测试):
public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
console.log(state.url);
}
答案 2 :(得分:0)
您可以使用ActivatedRouteSnapshot
和RouterStateSnapshot
来解决问题。
以下是我的Angular2应用程序中的代码示例。
AUTH-guard.ts
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { AuthCookie } from '../shared/services/auth-cookies-handler';
@Injectable()
export default class AuthGuard implements CanActivate {
constructor(private router: Router, private _authCookie: AuthCookie) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
if (this._authCookie.getAuth()) {
//add your custom conditions for route nevigation
return true;
}
else {
this.router.navigate(['/login']);
return false;
}
}
}
app.routing.ts
import {ModuleWithProviders } from '@angular/core';
import {Routes, RouterModule } from '@angular/router';
import { HomeComponent } from '../home/home';
import {LoginComponent } from '../account/login';
import { RegisterComponent } from '../account/register';
import { JourneyComponent } from '../journey/journey.component';
import AuthGuard from './auth-guard';
const appRoutes: Routes = [
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
}, {
path: 'journey',
component: JourneyComponent,
children: [
{ path: '', redirectTo: 'details', pathMatch: 'full' },
{ path: 'details', component: JourneyDetailsComponent, canActivate: [AuthGuard] },
{ path: 'documents', component: DocumentsComponent, canActivate: [AuthGuard] },
{ path: 'review', component: ReviewComponent, canActivate: [AuthGuard] },
{ path: 'payment', component: PaymentComponent, canActivate: [AuthGuard] }
]
, canActivate: [AuthGuard]
},
{
path: 'application',
component: ApplicationComponent,
canActivate: [AuthGuard]
},
{
path: 'login',
component: LoginComponent
},
{
path: 'activate-account/:uid',
component: AccountComponent
},
{
path: 'reset-password/:uid',
component: ResetPasswordComponent
},
{
path: 'home',
component: HomeComponent
},
{
path: 'register',
component: RegisterComponent
}
];
export const appRoutingProviders: any[] = [
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
希望这会对你有帮助!