如何防止Angular加载Component两次?

时间:2016-10-18 23:15:07

标签: angular typescript angular2-routing

我的Angular应用程序正在加载一个组件两次。最初,我在我的组件模板中有<router-outlet></router-outlet>,它工作正常,但仍然给我这些错误:

core.umd.js:3257 EXCEPTION: Uncaught (in promise): Error: Cannot find primary outlet to load 'AppComponent'
core.umd.js:3262 ORIGINAL STACKTRACE:
core.umd.js:3263 Error: Uncaught (in promise): Error: Cannot find primary outlet to load 'AppComponent'
zone.js:355 Unhandled Promise rejection: Cannot find primary outlet to load 'AppComponent' ; Zone: angular ; Task: Promise.then ; Value: Error: Cannot find primary outlet to load 'AppComponent'(…) Error: Cannot find primary outlet to load 'AppComponent' 
zone.js:357 Error: Uncaught (in promise): Error: Cannot find primary outlet to load 'AppComponent'

要解决这些错误,我将<router-outlet></router-outlet>添加到了我的模板中。但现在我的应用程序正在加载我的组件两次。

app.component.ts

import { Component } from '@angular/core';

@Component({
moduleId: module.id
  selector:'body', 
  templateUrl: 'app.component.html', 
  styleUrls: ['app.component.css']
})

export class AppComponent {
  title = 'Doctor Application';
}

应用-routing.module.ts

import { NgModule }             from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { AppComponent }   from './app.component';

const routes: Routes = [
  { path: '', component: AppComponent  },
];

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

export class AppRoutingModule {}

app.component.html

<h1>{{title}}</h1>
<router-outlet></router-outlet>

1 个答案:

答案 0 :(得分:2)

AppComponent不应该成为路由的一部分。它曾用于引导。这就是错误的含义。您正在尝试将AppComponent添加到路由中,但它没有<router-outlet>,因为它是顶级组件。