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

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

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

当前回答

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

其他回答

通过路由将路由参数从一个组件发送到另一个组件有三种方式。但是首先要将这些库导入到与.ts文件相关的组件中,并在构造函数中进行定义

private route: ActivatedRoute
private router: Router

第一种方式:必需的路由参数

//Route Configuration
{path: 'user/:id', component: UserDetailComponent}

//Set Hyperlink/routerLink
<a [routerLink]="['/user', user.id]"></a> 

 //Requesting Url after click on hyperlink
 http://localhost:4200/user/6

//Now you can read id value in navigated component
this.route.snapshot.paramMap.get('id');

第二种方式:可选路径参数

//Route Configuration
    {path: 'user', component: UserDetailComponent}
    
    //Set Hyperlink/routerLink
    <a [routerLink]=['/user', {name: userName, status: true}]"></a>


//Requesting Url after click on hyperlink
    http://localhost:4200/user;name:userNameValue;status:true

//Now you can read values in navigated component
    this.route.snapshot.paramMap.get('userId');
    this.route.snapshot.paramMap.get('userName');

第三种方式:可选路径参数

//Route Configuration
    {path: 'user', component: UserDetailComponent}
    
    //Set Hyperlink/routerLink
    <a [routerLink]="['/user']"  [queryParms]="{userId:'911', status:true}"></a>

    //Requesting Url after click on hyperlink
    http://localhost:4200/user?userId=911&status=true

    
    //Now you can read values in navigated component
    this.route.snapshot.paramMap.get('userId');
    this.route.snapshot.paramMap.get('userName');

参考:https://qastack.mx/programming/44864303/send-data-through-routing-paths-in-angular

使用这个匹配器函数,您可以在不重新渲染组件的情况下获得理想的行为。当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,
  }]

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

@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

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

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

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

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

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

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