【问题标题】:Angular 7 duplicate component rendered in router-outlet在路由器插座中呈现的Angular 7重复组件
【发布时间】:2022-01-14 16:59:01
【问题描述】:

这只是偶尔发生(通常在早上打开应用程序之后)。

我们正在使用 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>

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

【问题讨论】:

  • 不,那是渲染的结果。我应该添加索引吗?
  • 不,我的错! :)
  • 能先排除没有错误吗?发生这种情况时是否打开了浏览器控制台?
  • 是的,浏览器控制台没有错误
  • 你的 app-root 组件的 html 中是否只包含 ?

标签: angular angular7 router-outlet


【解决方案1】:

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

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


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

【讨论】:

    【解决方案2】:

    您可以尝试删除app.component.html 中的component router 插座除外。

    【讨论】:

    • 你能解释一下如何解决这个问题吗?
    猜你喜欢
    • 1970-01-01
    • 2019-10-15
    • 2018-07-28
    • 2017-07-02
    • 2019-06-20
    • 2019-06-28
    • 1970-01-01
    • 2016-12-30
    • 2017-06-09
    相关资源
    最近更新 更多