I want to redirect a route to another route:
/foo/bar/123 schould redirect to /bar/123;mode=test
I configured the route in the following way:
{ path: 'foo/bar/:id', redirectTo: '/bar/:id;mode=test' },
When it is redirecting, the ;mode=test
part is missing in the target url. How can I include this?
the angular router basically looks at path objects and creates the set of basic routes of your app (without the optional parameters). which then would be used to recognize routes if they match the path exactly. so the optional parameters cannot be used inside them because they're "optional". and the only way to include any route params in these path objects, is binding them inside the url with':something' syntax which then wouldn't be optional. i think you have some other ways to cover this need of your's:
adding your "mode" parameter to your basic route:
you can define a path like this: { path:'/bar/:id/:mode', component: BarComponent }
and change your redirect path to { path: 'foo/bar/:id', redirectTo: '/bar/:id/test' }
using a proxy component:
change the redirect path to: { path: 'foo/bar/:id', component: BarProxyComponent }
, and define that component like this:
export class BarProxyComponent {
constructor(private _router: Router, private _route: ActivatedRoute){
_router.navigate(['/bar/'+_route.snapshot.params['id'],{mode: 'test'}]);
}
}
using an canActivate Guard: you can also create a guard service for your 'foo' path, and inside the guard redirect it to the route you want. however, it's not exactly the real intention behind these guards and it's just taking advantage of them for that said problem.
you can change the redirect path to { path: 'foo/bar/:id', component: UnusedFooComponent, canActivate: [FooGuard]}
and define the guard like this:
@Injectable()
export class FooGuard implements CanActivate {
constructor(private _router: Router){}
canActivate(route: ActivatedRouteSnapshot) {
this._router.navigate(['/bar/'+route.params['id'],{mode: 'test'}]);
return false;
}
}
also dont forget to provide the FooGuard
at a module level.
and note that here, you're always redirecting to another place (and returning false) in the guard before the UnusedFooComponent
is created...