【问题标题】:Angular 6 same router.navigate causes refresh when called from another component从另一个组件调用时,Angular 6 相同的 router.navigate 会导致刷新
【发布时间】:2018-06-15 14:53:36
【问题描述】:

我有一个路由模块如下:

应用路由模块

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 导航,附加一个?然后重新加载页面。我在这里遗漏了什么,为什么当 activateRoute 对象相同时,两个看似相似的调用会产生如此不同的结果?

【问题讨论】:

    标签: angular typescript angular-router


    【解决方案1】:

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

    【讨论】:

    • 将按钮移出表单。也可以通过从表单中删除 ngSubmit 或添加它并从按钮中删除单击处理程序来解决。两种方法按钮都在表单标签内
    【解决方案2】:

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

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

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

    重要的部分是,这样做:

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

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

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

    我个人认为,FWIW,嵌套路由器插座很酷,而且它们提供了大量的电力,但它们也给您的应用程序带来了很多复杂性。酌情使用它们,但要明智地使用它们,并在可能的情况下倾向于更扁平的结构。

    【讨论】:

      猜你喜欢
      • 2020-02-04
      • 2019-06-22
      • 1970-01-01
      • 1970-01-01
      • 2018-11-30
      • 1970-01-01
      • 2018-11-27
      • 2019-07-05
      • 2017-07-31
      相关资源
      最近更新 更多