Joh*_*hni 8 angular-routing angular
我想将路线重定向到另一条路线:
/ foo/bar/123 schould重定向到/ bar/123; mode = test
我按以下方式配置了路由:
{ path: 'foo/bar/:id', redirectTo: '/bar/:id;mode=test' },
当它重定向时,;mode=test目标URL中缺少该部分.我怎么能包括这个?
角路由器基本上会查看路径对象,并创建应用的基本路由集(不带可选参数)。然后,如果它们与路径完全匹配,它将用于识别路由。因此可选参数不能在其中使用,因为它们是“可选”的。而在这些路径对象中包含任何路由参数的唯一方法是使用':something'语法将它们绑定在url中,这将不是可选的。我认为您还有其他方法可以满足您的需求:
在基本路由中添加“ mode”参数:
您可以定义如下路径:{ path:'/bar/:id/:mode', component: BarComponent }并将重定向路径更改为{ path: 'foo/bar/:id', redirectTo: '/bar/:id/test' }
使用代理组件:
将重定向路径更改为:{ path: 'foo/bar/:id', component: BarProxyComponent },然后按以下方式定义该组件:
export class BarProxyComponent {
constructor(private _router: Router, private _route: ActivatedRoute){
_router.navigate(['/bar/'+_route.snapshot.params['id'],{mode: 'test'}]);
}
}
Run Code Online (Sandbox Code Playgroud)
使用canActivate Guard:您还可以为“ foo”路径创建一个保护服务,并在保护内部将其重定向到所需的路由。但是,这并不是这些警卫的真正意图,而只是利用它们来解决上述问题。您可以将重定向路径更改为{ path: 'foo/bar/:id', component: UnusedFooComponent, canActivate: [FooGuard]}并定义防护,如下所示:
@Injectable()
export class FooGuard implements CanActivate {
constructor(private _router: Router){}
canActivate(route: ActivatedRouteSnapshot) {
this._router.navigate(['/bar/'+route.params['id'],{mode: 'test'}]);
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
也不要忘记FooGuard在模块级别提供。请注意,在这里,您总是在UnusedFooComponent创建之前将其重定向到防护中的另一个位置(并返回false)...
| 归档时间: |
|
| 查看次数: |
15078 次 |
| 最近记录: |