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

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

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

当前回答

使用这个匹配器函数,您可以在不重新渲染组件的情况下获得理想的行为。当url。长度等于0,没有可选参数,url。长度等于1,有1个可选参数。Id -可选参数名称。

  const routes: Routes = [
  {
    matcher: (segments) => {
      if (segments.length <= 1) {
        return {
          consumed: segments,
          posParams: {
            id: new UrlSegment(segments[0]?.path || '', {}),
          },
        };
      }
      return null;
    },
    pathMatch: 'prefix',
    component: UserComponent,
  }]

其他回答

我不能评论,但参考:Angular 2的可选路由参数

Angular 6的更新:

import {map} from "rxjs/operators"

constructor(route: ActivatedRoute) {
  let paramId = route.params.pipe(map(p => p.id));

  if (paramId) {
    ...
  }
}

有关Angular6路由的更多信息,请参阅https://angular.io/api/router/ActivatedRoute。

你可以定义多个带参数和不带参数的路由:

@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

使用angular4,我们只需要在层次中组织路由

const appRoutes: Routes = [
  { 
    path: '', 
    component: MainPageComponent 
  },
  { 
    path: 'car/details', 
    component: CarDetailsComponent 
  },
  { 
    path: 'car/details/platforms-products', 
    component: CarProductsComponent 
  },
  { 
    path: 'car/details/:id', 
    component: CadDetailsComponent 
  },
  { 
    path: 'car/details/:id/platforms-products', 
    component: CarProductsComponent 
  }
];

这对我很有用。这样路由器就可以根据选项id参数知道下一个路由是什么。

遇到了这个问题的另一个例子,为了寻找解决方案,我来到了这里。我的问题是,我正在做的孩子,和惰性加载组件以及优化事情一点。简而言之,如果你懒于加载父模块。主要的事情是我在路线中使用'/:id',它抱怨'/'是它的一部分。这不是真正的问题,但它适用。

从父应用程序路由

...
const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: 'pathOne',
        loadChildren: 'app/views/$MODULE_PATH.module#PathOneModule'
      },
      {
        path: 'pathTwo',
        loadChildren: 'app/views/$MODULE_PATH.module#PathTwoModule'
      },
...

子路由惰性加载

...
const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: '',
        component: OverviewComponent
      },
      {
        path: ':id',
        component: DetailedComponent
      },
    ]
  }
];
...

Rerezz的回答很不错,但它有一个严重的缺陷。它会导致User组件重新运行ngOnInit方法。

当你在那里做一些繁重的工作时它可能会有问题当你从非参数路线切换到参数路线时,你不希望它重新运行。虽然这两个路由是为了模仿一个可选的url参数,而不是成为两个独立的路由。

下面是我解决这个问题的建议:

const routes = [
  {
    path: '/user',
    component: User,
    children: [
      { path: ':id', component: UserWithParam, name: 'Usernew' }
    ]
  }
];

然后,您可以将负责处理参数的逻辑移动到UserWithParam组件,并将基本逻辑留在User组件中。无论你在User::ngOnInit中做什么,当你从/ User导航到/ User /123时,都不会再次运行。

不要忘记在User的模板中放入<router-outlet></router-outlet>。