我有一个以这种方式使用惰性模块的应用程序:
export const routes: Routes = [
{
path: '',
component: WelcomeComponent
},
{
path: 'items',
loadChildren: 'app/modules/items/items.module#ItemsModule'
}
];
export const AppRoutingModule: ModuleWithProviders
= RouterModule.forRoot(routes);
在 ItemsModule
中,我想为其中一个子路由使用守卫:
const routes: Routes = [
{
path: ':slug', component: ItemComponent,
canActivate: [ ItemFetchGuard ]
}
];
export const coveragesRoutingModule: ModuleWithProviders =
RouterModule.forChild(routes);
这个守卫需要获取slug
参数来获取数据:
@Injectable()
export class CoverageFetchGuard implements CanActivate {
constructor(
private service: ItemService,
private route: ActivatedRouteSnapshot,
private ngRedux: NgRedux<IAppState>) {}
canActivate() {
const slug = this.route.params['slug'];
return this.service.getItem(slug)
.map(item => {
this.ngRedux.dispatch(itemSuccessfullyFetched(item));
return true;
})
.catch(error => {
this.ngRedux.dispatch(itemFetchFailed(error));
return Observable.of(false);
});
}
}
问题是我无法在路由快照中找到 slug
参数(即使在其 children
属性中)。好像这个数据以后可以用但是我找不到办法获取它...
实现它的方法是什么?感谢您的帮助!
最佳答案
我终于找到了“问题”(实际上不是问题)。我没有以正确的方式使用守卫。我们需要使用有关利用 canActivate
方法参数的当前路由的提示,而不是尝试从依赖注入(inject)中获取它们。
获取参数的方法如下:
@Injectable()
export class ItemFetchGuard implements CanActivate {
canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot) {
const slug = this.snapshot.params['slug'];
(...)
return true;
}
}
这是相应的plunkr:http://plnkr.co/edit/UVz5YUkK0JoAy0i64Lo3?p=preview
关于angular - 无法获取 CanActivate 守卫中惰性模块的路由参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41125823/