在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 8中,你可以在不改变路由器配置的情况下简单地添加参数。

可选参数

在yourModule.routing.module.ts

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

在模板中:

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

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

@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

我不能评论,但参考: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。

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

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之类的)。

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

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