【问题标题】:Angular passing parameters to route cannot match routes角度传递参数到路由不能匹配路由
【发布时间】:2020-07-16 00:22:44
【问题描述】:

我正在尝试导航到一个应该接受 2 个 url 参数的组件,但由于某种原因,我收到一条错误消息,提示无法匹配路由

const routes: Routes = [
{
    path: 'home',
    component: HomeComponent
},
{
    path: 'home/:dataClass',
    },
    canActivate: [ProtectedRoutesGuard],
    component: DataViewerRouteComponent,
},
{ // PROBLEM ROUTE BELOW

    path: '/:dataClassName/:id',
    data: {
        name: 'Service Status'
    },
    component: DataViewerRecordsComponent,
},
{ 
    pathMatch: 'full',
    path: '',
    data: {
        name: 'Service Status',
        module: ['data-viewer']
    },
    canActivate: [ProtectedRoutesGuard],
    component: DataViewerHomeComponent,
},
{
    pathMatch: 'full',
    path: '**',
    redirectTo: '/data-viewer',
}

];

导航如下:

this.router.navigate([this.dataClassName + '/' + this.id]);

路由正在填充预期值,但未与任何路由匹配。 错误信息如下:

core.js:4002 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'benchmarks/101723102'

错误:无法匹配任何路由。 URL 段:'required/1234'

【问题讨论】:

  • 如果你有一个斜线怎么办,比如navigate(['/' + this.dataClassName + '/' + this.id])
  • @TadhgMcDonald-Jensen 不幸的是没有。尝试过并产生相同的错误。我认为问题出在我可能没有正确声明的路线[]中

标签: angular typescript


【解决方案1】:

您的路由应该如下所示:

this.router.navigate(['/'+this.dataClassName], {queryParams: {'id': this.id}});

然后您需要从路由到的组件中解析 queryParams。

【讨论】:

    【解决方案2】:

    navigateByUrl

    当您使用字符串导航时,您可以使用navigateByUrl

    this.router.navigateByUrl(`/${this.dataClassName}/${this.id}`);
    

    导航

    否则使用navigate时,需要提供url-segments(/分隔的部分)

    this.router.navigate([`/${this.dataClassName}`, this.id]);
    

    旁注:你可能不想只在你的路由中使用参数

    PS:如果我没记错的话,你不应该定义以/开头的路由

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-04
      • 2020-09-09
      • 1970-01-01
      • 2018-05-17
      • 2020-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多