Angular 6 default route not loading. How can I fix this?

yul-dev picture yul-dev · Jul 30, 2018 · Viewed 7.2k times · Source

I have an angular 6 project structured like bellow...

src
|- app
|  |- core
|  |  |- layout.component.ts/html/scss
|  |  |- core.module.ts
|  |- views
|  |  |- modules
|  |  |  |- sample
|  |  |  |  |- sample.component.ts/html/scss
|  |  |  |  |- sample-routing.module.ts
|  |  |  |  |- sample.module.ts
|- app.component.ts/html/scss
|- app-routing.module.ts
|- app.module.ts

...with the routing structure for sample module looking like...

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

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

...and app routing module looking like...

const routes: Routes = [
  {
    path: '',
    component: LayoutComponent,
    children: [
      {
        path: '',
        redirectTo: 'sample',
        pathMatch: 'full'
      },
      {
        path: 'sample',
        loadChildren: './views/sample/sample.module#SampleModule'
      }
    ]
  }
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

The behavior I'm noticing is that when I serve the app, the default base route that is supposed to be the layout component does not load. Instead I get a white screen with no errors in the console. Then if I type in http://localhost:4200/sample i get the correct behavior. Still that initial redirect is not happening that should load the layout component with the sample module within it. app.component.html has the <router-outlet></router-outlet> as well as the layout.component.html Have been looking at this trying to figure it out for longer than i care to admit. Perhaps the location of the layout component is more important than I think so it should be registered to the app module?

Answer

yul-dev picture yul-dev · Jul 30, 2018

I had a RouterModule imported and routes defined in an old unrelated module within the same project with a default route. Something like...

const routes = {
  {
     path: '',
     component: RandomComponent
  }
}
...
imports: [RouterModule.forChild(routes)]
...

Removing that fixed the routing I was trying to implement. Angular must have been trying to register some eager locations. Feel kinda dumb about it to be honest. Thanks to those who answered!