Angular 6 相同 router.navigate 从另一个组件调用时导致刷新

Angular 6 same router.navigate causes refresh when called from another component

我有一个路由模块如下:

应用路由模块

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。

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

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

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

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

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

导航栏位于根组件中,因此它是相对于路由器根“/”导航的。

CreateEditComponent 是 root 的路由子项,因此它是相对于路由器的第一个子项进行导航的,它可能是“/create”或其他任何内容,我不确定您的路由器究竟是如何根据问题构建的.但基本上,每次嵌套路由器出口/添加子路由时,都会在路由器树中创建一个新节点。

但重要的是,这样做:

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

前面有一个“/”将使它成为一个绝对 URL,无论从哪里调用它都会去同一个地方,因为它总是从根导航。

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

我个人认为,FWIW,嵌套路由器插座很酷,它们提供了大量的功能,但它们也会给您的应用程序带来很多复杂性。酌情使用它们,但要谨慎使用,并尽可能采用更扁平的结构。

终于弄清楚是什么导致了刷新。导致刷新的带有 (click) 处理程序的按钮位于 <form> 标记内。每当调用执行 router.navigate 的点击功能时,它都会导致提交表单,这似乎是

的原因