Mahammad Adil Azeem
Mahammad Adil Azeem

Reputation: 9392

How do I prevent Angular from loading a Component twice?

My Angular app is loading a component twice. Initially, I had <router-outlet></router-outlet> in my component's template and it was working fine but was still giving me these errors:

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'

To resolve these errors, I added <router-outlet></router-outlet> to my template. But now my app is loading my component twice.

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';
}

app-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>

Upvotes: 4

Views: 7641

Answers (2)

Canal do Monstro
Canal do Monstro

Reputation: 19

The app-component is load and is not necessary declare in the AppRoutingModule , if you add AppComponent in your Routing module he its load twice: app-routing.module.ts

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

import { AppComponent }   from './app.component'; **<- Remove this line **

const routes: Routes = [
  {
     path: '',
     component: AppComponent **<-Remove this line**
  },

];

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

export class AppRoutingModule {}

Upvotes: 1

Paul Samsotha
Paul Samsotha

Reputation: 208944

The AppComponent shouldn't be part of the routing. It's used to bootstrap. That's what the error is about. You're trying to add the AppComponent to the routing, but there's no <router-outlet> for it, because it is the top-level component.

Upvotes: 6

Related Questions