简体   繁体   中英

Angular route redirectTo with params

I have a problem with angular routing. In my app i had some routes like this:

[{
     path: 'myroutes/:id',
     component: BarComponent
 }, {
     path: 'myroutes/:id/:value',
     component: FooComponent
 }]

I want to change this routing, but the old routes must be redirected to the new ones. So i changed my code like this:

[{
    path: 'myroutes/:id/:value',
    redirectTo: 'myroute/:id/:value'
}, {
    path: 'myroutes/:id',
    component: BarComponent
}, {
    path: 'myroute/:id/:value',
    component: FooComponent
}]

With this routing im getting a NavigationError:

Cannot redirect to '/myroute/:id/:value'. Cannot find ':id'.

Changing the code to use fixed parameters in the redirectTo route solves the error, but the parameters must be dynamic.

The routes are imported with RouterModule.forRoot() .

Hoping this is sufficient information, otherwise feel free to ask for more. ;)

Thanks for your help! :)

Change path for redirectTo . You should prefix it with /

[{
    path: 'myroutes/:id/:value',
    redirectTo: '/myroute/:id/:value'
}, {
    path: 'myroutes/:id',
    component: BarComponent
}, {
    path: 'myroute/:id/:value',
    component: FooComponent
}]

You can create a simple Guard to redirect your old routes if nothing else works.

I think something like this should work:

app-routing.module.ts:

[{
  path: 'myroutes/:id/:value',
  canActivate: [
    forwarderGuard
  ]
}, {
  path: 'myroutes/:id',
  component: BarComponent
}, {
  path: 'myroute/:id/:value',
  component: FooComponent
}]

forwarder.guard.ts:

@Injectable()
export class forwarderGuard implements CanActivate {

  constructor(
    private router: Router
  ) { }

  canActivate(route: ActivatedRouteSnapshot) {
    this.router.navigate([`myroute/${route.params['id']}/${route.params['value']}`]);
    return false;
  }
}

I've solved my problem. The issue was that the parameter names in my app were written camelCase. When the parameter are written lower case everything is allright. :)

Thanks for your help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM