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

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

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

当前回答

面对类似的延迟加载问题,我做了这样的事情:

const routes: Routes = [
  {
    path: 'users',
    redirectTo: 'users/',
    pathMatch: 'full'
  },
  {
    path: 'users',
    loadChildren: './users/users.module#UserssModule',
    runGuardsAndResolvers: 'always'
  },
[...]

然后在组件中:

  ngOnInit() {
    this.activatedRoute.paramMap.pipe(
      switchMap(
        (params: ParamMap) => {
          let id: string = params.get('id');
          if (id == "") {
            return of(undefined);
          }
          return this.usersService.getUser(Number(params.get('id')));
        }
      )
    ).subscribe(user => this.selectedUser = user);
  }

这种方式:

没有/的路由被重定向到有/的路由。由于pathMatch: 'full',只有这样特定的完整路由才会被重定向。 然后接收到users/:id。如果实际路由是users/, id是"",那么在ngOnInit中检查它并相应地执行;否则,id就是id,继续。 组件的其余部分作用于selectedUser是否未定义(*ngIf之类的)。

其他回答

这里建议的答案,包括来自rerezz的接受答案,它建议添加多个路由条目。

然而,当路由表项之间发生变化时,即在带参数的路由表项和不带参数的路由表项之间,组件将被重新创建。

如果你想避免这种情况,你可以创建自己的路由匹配器来匹配这两个路由:

export function userPageMatcher(segments: UrlSegment[]): UrlMatchResult {
    if (segments.length > 0 && segments[0].path === 'user') {
        if (segments.length === 1) {
            return {
                consumed: segments,
                posParams: {},
            };
        }
        if (segments.length === 2) {
            return {
                consumed: segments,
                posParams: { id: segments[1] },
            };
        }
        return <UrlMatchResult>(null as any);
    }
    return <UrlMatchResult>(null as any);
 }

然后在路由配置中使用matcher:

const routes: Routes = [
    {
        matcher: userPageMatcher,
        component: User,
    }
];

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

可选参数

在yourModule.routing.module.ts

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

在模板中:

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

遇到了这个问题的另一个例子,为了寻找解决方案,我来到了这里。我的问题是,我正在做的孩子,和惰性加载组件以及优化事情一点。简而言之,如果你懒于加载父模块。主要的事情是我在路线中使用'/: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
      },
    ]
  }
];
...

主细节视图也有同样的问题。主视图可以在没有: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。

使用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参数知道下一个路由是什么。