evan
evan

Reputation: 1118

AngularJS2 component not loading after adding router

AngularJS2 app component is not loading after adding the router. There is no error in the log. if I remove the router it starts working again. Does anyone faced this kind of issue before. I am using 'lite-server' to run the application.

angular js version : "2.4.0",
router version : "~3.4.8",
lite-server version: "^2.2.2",

This is how I add router to my app.

step 1: added '<base href="/">' to index.html

step 2: added router links to my component.html

  <nav>
    <a routerLink="/new">Contacts</a> 
  </nav>
  <router-outlet></router-outlet> 

step 3: my router.ts looks like below

export const routes: Routes = [
      { path: '', component: ContactListComponent },
      { path: '/new', component: NewContactComponent },
      { path: '/about', component: AboutComponent }
];


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

step 4: added routing component to the module like below

@NgModule({
  declarations: [
    AppComponent,
    ContactListComponent,
    ContactComponent,
    NewContactComponent,
    AboutComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    AppRoutingModule
  ],
  providers: [ContactService],
  bootstrap: [AppComponent]
})

Also tried to inject router like below

export class AppComponent {

   constructor(private routes: Router) { 

   }

}

So can anyone tell me what I am doing wrong?

Upvotes: 0

Views: 139

Answers (1)

mickdev
mickdev

Reputation: 2865

Try with no slash (/) :

export const routes: Routes = [
      { path: '', component: ContactListComponent },
      { path: 'new', component: NewContactComponent },
      { path: 'about', component: AboutComponent }
];

With slashes you'll probably get an error ("path cannot start with a slash...").

Upvotes: 1

Related Questions