【问题标题】:Angular loads two components simultaneouslyAngular 同时加载两个组件
【发布时间】:2018-04-10 11:48:58
【问题描述】:

我有一个使用 angular2 作为前端部分的应用程序。有时我遇到了很奇怪的错误:登录应用程序后,我同时看到两个组件(登录组件和主组件)。

因此,在上面的屏幕截图中,不应该看到登录功能的输入。

这是所提供页面的 html 代码。
下面我列出了app.component.html的内容:

<form name="header" class="form-horizontal" >
<div class="navbar-fixed-top cometflowHeader">
    <label>CometFlow</label>
</div>
</form>

<div class="jumbotron" style="background-color: #fff; border: 3px; border-color: black;">
    <div class="classol-sm-12">
        <router-outlet></router-outlet>
    </div>
</div>

以及路由配置:

const appRoutes: Routes = [
  {path: 'login', component: LoginComponent},
  {path: '', component: HomeComponent, canActivate: [AuthGuard], pathMatch: 'full'},

  // otherwise redirect to home
  {path: '**', redirectTo: ''}
];

export const routing = RouterModule.forRoot(appRoutes, {useHash: true});

@NgModule({
  imports: [
      ...,
      routing
  ],
  bootstrap: [AppComponent]
})

有人可以告诉我应该在哪里寻找问题吗?因为现在我不知道为什么会这样。我在浏览器的控制台中没有看到任何错误。

【问题讨论】:

  • 我遇到了同样的问题,但现在不记得我的代码的确切问题是什么。但是在某个地方调用了第二个组件。仔细检查你的代码,看看你的第二个组件来自哪里。
  • 进行调试,在你的方法或可疑代码的某个地方使用打字稿中的debugger 来调试你认为错误可能来自哪里
  • 是你的第一个组件调用它里面的第二个组件。当你调用第一个时,它会自动调用第二个。
  • @WASIF,我不确定这与我的组件的额外调用有关。因为应用程序并非每次都这样。这可能发生在 1% 中。如果我按下页面上的SMS Campaign 链接,我将在同一页面上看到第三个组件。在第三个组件上按下某些东西后,我会看到第四个组件以及前三个组件。

标签: angular angular2-routing


【解决方案1】:

我认为您的路由不正确。 HomeComponent应该是AppComponent的孩子吧?

我认为应该是这样的:

const appRoutes: Routes = [
  {
    path: 'login',
    component: LoginComponent
  },
  {
    path: '',
    component: AppComponent,
    children: [
      {
        path: '',
        component: HomeComponent,
        canActivate: [AuthGuard],
        pathMatch: 'full'
      },

      // otherwise redirect to home
      { path: '**', redirectTo: '' }
    ]
  }
];

或者像这样:

const appRoutes: Routes = [
  {
    path: '',
    component: AppComponent,
    children: [
      {
        path: '',
        component: HomeComponent,
        canActivate: [AuthGuard],
        pathMatch: 'full'
      },
      {
        path: 'login',
        component: LoginComponent
      },
      // otherwise redirect to home
      { path: '**', redirectTo: '' }
    ]
  }
];

您的&lt;router-outlet&gt;&lt;/router-outlet&gt; 应该是哪些组件的出口?

【讨论】:

    【解决方案2】:

    我找到了解决问题的方法here
    简而言之:BrowserAnimationsModule 存在错误。我升级了 Angular 的版本,之后这个视觉缺陷就消失了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-16
      • 2019-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-24
      • 2017-06-24
      • 2021-12-11
      相关资源
      最近更新 更多