Angular2+ 路由 - 可选路由参数

Angular2+ routing - optional route params

所以我有 /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}

So is there any way to define these type routes with optional params like we do in ExpressJS

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

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

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

截至目前,Angular 不允许您定义可选参数。所以你的解决方案是添加多条相似的路线——都指向同一个组件。但是这里有一件重要的事情需要注意。如果在两个路由中都使用target为component: ItemsComponent,由于路由不同,组件会被重新实例化! - 这可能会很昂贵,具体取决于您的项目。如果您不想为每个路由重新实例化组件,请改用 redirect。在这种情况下 Angular 确保组件只被实例化一次。

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

希望对您有所帮助!