Angular `<router-outlet>` 显示模板两次

Angular `<router-outlet>` displays template twice

我正在使用 angular4 并尝试创建一个路由器 link。路由器 link 工作但显示模板两次。

下面是我在组件中的代码:

import { Component } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-root',
  template: `
  <h1>Contacts App</h1>
    <ul>
      <li><a [routerLink]="['/facebook/top']">Contact List</a></li>
    </ul>
    <router-outlet></router-outlet>
    `
})
export class AppComponent {
    constructor(
        private route: ActivatedRoute,
        private router: Router,
    ){ }

    gotoDetail(): void {
        this.router.navigate(['facebook/top']);
    }
}

我的路线:

const routes: Routes = [
  { path: '', component: AppComponent },
  { path: 'facebook/top',  component: CommentComponent },
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

您的默认路线指向 AppComponent,因此您的路线在 AppComponent 内呈现 AppComponent

为此创建一个 DashboardComponentHomeComponent。然后做:

{ path: '', component: DashboardComponent }

更新 1:

正如@GünterZöchbauer 提到的,我们应该为 "an empty path route with no children".

添加 pathMatch: 'full'

所以我们可以采用 AppComponent 方法 (检查 :

{ path: '', component: AppComponent, pathMatch: 'full' }

或者,我在回答中提到的 DashboardComponent 方法。

为什么会这样?

1) 在您的应用程序入口点,最有可能 main.ts,可以阅读以下行:

platformBrowserDynamic().bootstrapModule(AppModule);

这告诉 angular 到 bootstrap 模块 AppModule

2) 在AppModule中,可以找到这一行:

bootstrap: [ AppComponent ]

这告诉 angular 到 bootstrap 组件 AppComponent。这就是为什么您看到第一个 Contacts App 部分的原因,因为 AppComponent 的 html 模板是:

<h1>Contacts App</h1>
<ul>
    <li><a [routerLink]="['/facebook/top']">Contact List</a></li>
</ul>
<router-outlet></router-outlet>

3) 但是,您的 AppComponent 的模板也包含 <router-outlet>。路由器读取路由配置,相应地创建一个 AppComponent 的新实例,并在元素 <router-outlet> 之后立即注入它。这就是您看到第二个 Contacts App 部分的原因。

如果你有没有children的空路径路线,使用pathMatch: 'full'

而不是

{ path: '', component: AppComponent },

使用

{ path: '', component: AppComponent, pathMatch: 'full' },

以及@SrAxi 所说的。

在您的应用程序-routing.module.ts 文件中尝试使用:

{path: '' , redirectTo: 'AppComponent', pathMatch: 'full'}

而不是:

{ path: '', component: AppComponent, pathMatch: 'full' }