Angular 6相同的router.navigate在从另一个组件

时间:2018-06-15 14:53:36

标签: angular typescript angular-router

我有一个路由模块如下:

应用路由模块

const routes: Routes = [
  {
    path: '',
    redirectTo: environment.devRedirect,
    pathMatch: 'full',
    canActivate: [AuthenticationGuard]
  },
  {
    path: 'customers/:customerId/contracts/:contractId',
    loadChildren: './grouping/grouping-routing.module#GroupingRoutingModule'
    canActivate: [AuthenticationGuard],
  }
];

带有路线的子组件:

const routes: Routes = [
      {
        path: 'create',
        component: CreateEditComponent,
        data: { animation: 'create' },
        canActivate: [ AuthenticationGuard ]
      },
      {
        path: ':groupId/edit',
        component: CreateEditComponent,
        data: { animation: 'edit' },
        canActivate: [ AuthenticationGuard ]
      },
      {
        path: '',
        component: OverviewComponent,
        data: { animation: 'overview' },
        canActivate: [ AuthenticationGuard ]
      }
];

我有一个位于app.component.html的顶级导航栏组件。

navbar组件和CreateEditComponent都有一个如下所示的函数。使用(单击)按钮调用两者:

  goToOverview(): void {
    this._router.navigate(['customers/:customerId/contracts/:contractId']);
  }

当我调试路由器对象时,两者看起来完全相同,即具有所有相同的路径等。

我的问题是导航栏功能正确路由,但CreateEditComponent导航,附加一个?然后重新加载页面。我在这里错过了什么,为什么当activatedRoute对象相同时,两个看似相似的调用会产生如此不同的结果?

2 个答案:

答案 0 :(得分:1)

您正在使用相对URL,这意味着您相对于路由器树中的当前组件位置进行导航。

Navbar位于根组件中,因此它相对于路由器根目录导航,即“/”。

CreateEditComponent是root的路由子节点,因此它相对于路由器第一个子节点导航,可能是“/ create”或者其他什么,我不确定你的路由器是如何构建的。但基本上,每次嵌套路由器插座/添加子路由时,都会在路由器树中创建一个新节点。

重要的一点是,这样做:

onrec
前面带有“/”的

将使它成为一个绝对的URL,无论它从何处被调用,它都会到达同一个地方,因为它总是从根目录导航。

您可能会看到奇怪的刷新行为,因为您尝试导航到无效路由并导致错误处理错误。

我个人认为,FWIW,嵌套式路由器插座很酷,而且它们提供了大量的功能,但它们也会在应用程序中造成很大的复杂性。在适当时使用它们,但在使用时要明智,并尽可能倾向于更平坦的结构。

答案 1 :(得分:1)

最后想出了导致刷新的原因。导致刷新的(click)处理程序按钮位于<form>标记内。每当调用click函数时,路由器都会调用它。导致它导致表单提交,这似乎是原因

相关问题