在Angular 2的路由中可以有一个可选的路由参数吗?我尝试了Angular 1。但是在routecconfig中收到如下错误:

“ORIGINAL EXCEPTION: Path /user/:id?”包含“?”,这在路由配置中是不允许的。

@RouteConfig([
{
    path: '/user/:id?',
    component: User,
    as: 'User'
}])

当前回答

主细节视图也有同样的问题。主视图可以在没有:elementId参数的情况下显示,但仍然应该显示详细选择并在url中显示:elementId。

我是这样解决的:

const routes: Routes = [
  {
    path: '',
    component: MasterDetailComponent,
    children: [
      {
        path: ':elementId',
        children: [
          {
            path: 'details',
            component: DetailComponent
          },
          {
            path: '',
            redirectTo: 'details'
          }
        ]
      }
    ]
  }
];

然后在MasterDetailComponent中(例如在ngOnInit方法中),你可以使用子路由获得:elementId:

const childRouteWithElementId = this.route.snapshot.children[0];
const elementIdFromUrl = childRouteWithElementId.params.elementId;
if (!!elementIdFromUrl ) {
  // Do what you need to with the optional parameter
}

当然,你也可以在没有子路由的情况下做同样的事情,只在url的末尾有可选的elementId。

其他回答

Angular 4 -解决可选参数排序的方案:

这样做:

const appRoutes: Routes = [
  {path: '', component: HomeComponent},
  {path: 'products', component: ProductsComponent},
  {path: 'products/:id', component: ProductsComponent}
]

注意,products和products/:id路由的命名完全相同。对于没有参数的路由,Angular 4会正确地遵循products,如果有参数,它会遵循products/:id。

然而,非参数路由产品的路径不能有后面的斜杠,否则angular会错误地将其视为参数路径。在我的例子中,我用后面的斜杠表示产品,但它不起作用。

不要这样做:

...
{path: 'products/', component: ProductsComponent},
{path: 'products/:id', component: ProductsComponent},
...

主细节视图也有同样的问题。主视图可以在没有:elementId参数的情况下显示,但仍然应该显示详细选择并在url中显示:elementId。

我是这样解决的:

const routes: Routes = [
  {
    path: '',
    component: MasterDetailComponent,
    children: [
      {
        path: ':elementId',
        children: [
          {
            path: 'details',
            component: DetailComponent
          },
          {
            path: '',
            redirectTo: 'details'
          }
        ]
      }
    ]
  }
];

然后在MasterDetailComponent中(例如在ngOnInit方法中),你可以使用子路由获得:elementId:

const childRouteWithElementId = this.route.snapshot.children[0];
const elementIdFromUrl = childRouteWithElementId.params.elementId;
if (!!elementIdFromUrl ) {
  // Do what you need to with the optional parameter
}

当然,你也可以在没有子路由的情况下做同样的事情,只在url的末尾有可选的elementId。

{path: 'users', redirectTo: 'users/', pathMatch: 'full'},
{path: 'users/:userId', component: UserComponent}

这样,在添加参数时就不会重新呈现组件。

在Angular 8中,你可以在不改变路由器配置的情况下简单地添加参数。

可选参数

在yourModule.routing.module.ts

const routes: Routes = [
  { path: 'somePath/:RequiredParam', component: Yourcomponent }
];

在模板中:

<div [RouterLink] = ['somePath', requiredParamValue, {optionalParam: value}]></div>

当信息为可选时,建议使用查询参数。

路由参数还是查询参数? 没有硬性规定。一般来说, 时优先使用路由参数 该值是必选项。 用于区分不同的路由路径。 时首选查询参数 可选参数。 该值为复杂和/或多变量。

从https://angular.io/guide/router optional-route-parameters

您只需要从路由路径中取出参数。

@RouteConfig([
{
    path: '/user/',
    component: User,
    as: 'User'
}])