Angular2 +路由-可选的路由参数

时间:2018-06-25 04:23:31

标签: angular angular-ui-router angular2-routing

所以我有/category/tech/category/tech/new/category/tech/old等路线

他们都使用ItemsComponent

所以有什么方法可以像在ExpressJS中那样用可选的参数定义这些类型的路由

router.get('/category/tech/:filter?', (req, res) => ...

/category/tech/category/tech/xxx都可以使用)

还是我必须像这样单独定义它们

{path: 'users', component: ItemsComponent},
{path: 'users/:filter', component: ItemsComponent}

2 个答案:

答案 0 :(得分:4)

  

那么有没有办法用可选的参数定义这些类型的路由   就像我们在ExpressJS中所做的一样

简单的答案是“否”,您必须为每个单独的路径定义新的路线。

{path: 'users', component: ItemsComponent},
{path: 'users/:filter', component: ItemsComponent}

尽管您可以验证路径并确定使用component在路由的ActivatedRoute中是否具有可选参数。

答案 1 :(得分:2)

到目前为止,Angular不允许您定义可选参数。因此,您的解决方案将是添加多个相似的路由-所有路由都指向同一组件。但是这里有一件重要的事情要注意。如果在两个路由中都将目标用作component: ItemsComponent,则由于路由不同,将重新实例化该组件! -根据您的项目,可能会很昂贵。如果不想为每个路由重新实例化组件,请使用redirect。在这种情况下,Angular确保仅实例化该组件一次。

{path: 'users', redirectTo: 'users/'},
{path: 'users/:filter', component: ItemsComponent}

希望这会有所帮助!

相关问题