在 Angular 2 路由中是否可以有一个可选的路由参数?我在 RouteConfig 中尝试了 Angular 1.x 语法,但收到以下错误:
“原始例外:路径“/user/:id?”包含“?”,这在路由配置中是不允许的。”
@RouteConfig([
{
path: '/user/:id?',
component: User,
as: 'User'
}])
在 Angular 2 路由中是否可以有一个可选的路由参数?我在 RouteConfig 中尝试了 Angular 1.x 语法,但收到以下错误:
“原始例外:路径“/user/:id?”包含“?”,这在路由配置中是不允许的。”
@RouteConfig([
{
path: '/user/:id?',
component: User,
as: 'User'
}])
您可以使用和不使用参数定义多个路由:
@RouteConfig([
{ path: '/user/:id', component: User, name: 'User' },
{ path: '/user', component: User, name: 'Usernew' }
])
并处理组件中的可选参数:
constructor(params: RouteParams) {
var paramId = params.get("id");
if (paramId) {
...
}
}
另请参阅相关的 github 问题:https : //github.com/angular/angular/issues/3525
{path: 'users', redirectTo: 'users/', pathMatch: 'full'},
{path: 'users/:userId', component: UserComponent}
这样,当添加参数时,组件不会重新渲染。
当信息是可选的时,建议使用查询参数。
路由参数还是查询参数?
没有硬性规定。一般来说,
更喜欢路由参数时
- 该值是必需的。
- 该值对于区分一条路由路径和另一条路由路径是必要的。
更喜欢查询参数时
- 该值是可选的。
- 该值是复杂的和/或多变量的。
来自https://angular.io/guide/router#optional-route-parameters
您只需要从路由路径中取出参数即可。
@RouteConfig([
{
path: '/user/',
component: User,
as: 'User'
}])
Angular 4 - 解决可选参数排序的解决方案:
做这个:
const appRoutes: Routes = [
{path: '', component: HomeComponent},
{path: 'products', component: ProductsComponent},
{path: 'products/:id', component: ProductsComponent}
]
请注意,products
和products/:id
路由的名称完全相同。products
对于没有参数的路由,Angular 4 将正确遵循,如果有参数,它将遵循products/:id
.
然而,对于非参数路由路径products
必须不能有斜线,否则角度将错误地把它当作一个参数路径。所以就我而言,我有产品的尾随斜线,但它不起作用。
不要这样做:
...
{path: 'products/', component: ProductsComponent},
{path: 'products/:id', component: ProductsComponent},
...
rerezz 的回答非常好,但它有一个严重的缺陷。它会导致User
组件重新运行该ngOnInit
方法。
当您在那里执行一些繁重的工作并且在从非参数路由切换到参数路由时不希望它重新运行时,这可能会出现问题。尽管这两条路由旨在模仿可选的 url 参数,但不会成为 2 条独立的路由。
以下是我解决问题的建议:
const routes = [
{
path: '/user',
component: User,
children: [
{ path: ':id', component: UserWithParam, name: 'Usernew' }
]
}
];
然后你可以将负责处理参数的逻辑移到UserWithParam
组件中,并将基本逻辑留在User
组件中。User::ngOnInit
当您从/user导航到/user/123时,无论您做什么都不会再次运行。
不要忘了把<router-outlet></router-outlet>
中User
的模板。