首页 > 解决方案 > 在路由器插座中呈现的 Angular 7 重复组件

问题描述

这只发生在某些时候(通常在早上打开应用程序之后)。

我们正在使用 SwUpdate 来更新应用程序,这种行为似乎与更新时间一致。结果 html 如下所示:

<app-root _nghost-vrt-c0="" ng-version="7.2.15">
  <router-outlet _ngcontent-vrt-c0=""></router-outlet>
  <app-layout _nghost-vrt-c4="">
    <div _ngcontent-vrt-c4="" class="app-class">
          <router-outlet _ngcontent-vrt-c4=""></router-outlet>
          <app-component-1 _nghost-vrt-c7="">
          </app-component-1>
          <app-component-1 _nghost-vrt-c7="">
          </app-component-1>
    </div>
  </app-layout>
</app-root>

问题是重复的 app-component-1。在正常情况下,它只渲染一次。我无法找到解决方案,甚至无法找到描述此问题的问题。感谢任何帮助。

相关路由规则:

const routes: Routes = [
  {
    path: '',
    component: Layout,
    canActivate: [AuthGuard],
    children: [
      { path: 'home', loadChildren: './home/home.module#HomeModule'},
      { path: 'otherRoute', loadChildren: './otherRoute/otherRoute.module#OtherRouteModule'},
      { path: '', redirectTo: 'home', pathMatch: 'full' },
    ]
  }
  { path: 'under-construction', component: UnderConstructionComponent, data: { title: 'Under Construction' } },
  { path: '**', redirectTo: 'under-construction' },
]

这是布局模板:

<div class="tm-app">
<div >
  <app-menu></app-menu>
  <div>
    <div>
      <app-top-bar></app-top-bar>
    </div>
    <router-outlet></router-outlet>
  </div>
</div>

我尽可能多地从布局和输出中清理,以保证代码库的安全。我正在编辑这个问题来解决它。因为我还没有找到解决办法。这个可以吗?

标签: angularangular7router-outlet

解决方案


在我的特殊情况下,问题与实现路由保护有关CanActivate。当守卫返回false时,路由无法激活(但它已经创建)。如果同时防护也重定向到另一个路由,则创建一个重复的路由器出口组件。

解决方案:不要从 route guard 重定向CanActivate。只返回真或假。替代解决方案:从CanActivate守卫重定向并始终返回 true(在守卫中重定向时)。


可以从守卫返回替代路由,这是比始终返回 true 更好的解决方案。


推荐阅读