Angular 路由 redirectTo 参数

Angular route redirectTo with params

我的 angular 路由有问题。在我的应用程序中,我有一些这样的路线:

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

我想更改此路由,但必须将旧路由重定向到新路由。所以我像这样更改了我的代码:

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

使用此路由我收到 NavigationError:

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

更改代码以在 redirectTo 路由中使用固定参数解决了错误,但参数必须是动态的。

路由是用RouterModule.forRoot()导入的。

希望这是足够的信息,否则请随时询问更多信息。 ;)

感谢您的帮助! :)

更改 redirectTo 的路径。你应该在它前面加上 /

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

如果其他方法都不起作用,您可以创建一个简单的 Guard 来重定向您的旧路由。

我认为这样的事情应该可行:

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;
  }
}

我的问题已经解决了。问题是我的应用程序中的参数名称是用驼峰式命名的。当参数写成小写时,一切都很好。 :)

感谢您的帮助!