![](/img/trans.png)
[英]Get target route URL in CanActivate guard Lazy load modules Angular
[英]Can't get route params for a lazy module within a CanActivate guard
我有一个使用惰性模块的应用程序:
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
方法的参数,而不是尝试从依赖注入中获取它们。
以下是获取参数的方法:
@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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.