Angular lazy loading routing always goes to wildcard module

Viewed 1260

I am working on a new Angular application that has multiple modules. I am still struggling to get my routing correct. In the following (simplified) example, I want to lazy load the StoreModule. If no url is given, I want my application to redirect to /store. If an invalid URL is given, I want my NotFoundComponent to be shown. In my current configuration however, the NotFoundComponent is always shown, regardless of the URL. Do you guys see what I am doing wrong?

This is my app.module.ts file, I would expect it to only use the RouterModule provided in NotFoundModule if no URL matches can be made.

app.module.ts

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AuthModule,
    RouterModule.forRoot([
      { path: '', redirectTo: 'store', pathMatch: 'full'},
      { path: 'store', loadChildren: 'app/store/store.module#StoreModule'},
      { path: 'login', component: LoginComponent },
    ]),
    LoginModule,
    NotfoundModule,
  ],
  bootstrap: [AppComponent],
  exports: [RouterModule]
})
export class AppModule { }

This is my StoreModule. If I comment out the NotFoundModule in my app.module.ts module this all works as expected.

store.module.ts

@NgModule({
  imports: [
    AuthModule,
    CommonModule,
    SharedModule,
    RouterModule.forChild([
      { path: '', pathMatch: 'full', redirectTo: 'dashboard' },
      { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
    ]),
  ],
  declarations: [StoreTemplateComponent, DashboardComponent]
})
export class StoreModule { }

notfound.module.ts

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild([
      {
        path: '**',
        component: NotfoundComponent
      }
    ])
  ],
  declarations: [ NotfoundComponent ],
})
export class NotfoundModule { }
2 Answers

Your router setting looks OK. One thing to look at is you have AuthGuard in 'dashboard' which must redirect and that redirecting URL must be wrong, so you are redirected to NotFoundComponent.

Hope this solves your problem.

If no url is given, I want my application to redirect to /store. If an invalid URL is given, I want my NotFoundComponent to be shown.

If this is the requirement then you need to remove notfound.module.ts . Or you need to load it lazily as in the present set up you are not loading it in your routes and by adding it in app modules it loads up front and treats all the routes as wild card.

you can just have a NotfoundComponent and add it to your existing routes.

RouterModule.forRoot([
  { path: '', redirectTo: 'store', pathMatch: 'full'},
  { path: 'store', loadChildren: 'app/store/store.module#StoreModule'},
  { path: 'login', component: LoginComponent },
  { path: '**', component: NotfoundComponent } // this should work
]),
Related