404 pages and Lazy Loading in Angular2

2020-07-17 04:45发布

问题:

I am unable to let my '404 pages' work using lazy loading modules. When I enter a random url in the browser I only see a blank page instead of my cool 404 page.

Here is my routing config

export const routes: Routes = [
  { path: '', redirectTo: 'dashboard', pathMatch: 'full'},
  { path: 'dashboard', loadChildren: 'app/dashboard/dashboard.module#DashboardModule'},
  { path: 'buckets', loadChildren: 'app/buckets/buckets.module#BucketsModule'},
  { path: '**', loadChildren: 'app/notfound/notfound.module#NotFoundModule'} 
];

export const routing: ModuleWithProviders = RouterModule.forRoot(routes);

When I surf to /buckets I see the chunk is being lazy loaded and it shows the appropriate component which is configured in the Buckets Module, thats ok.

But it doesn't work with 404 error pages. Normally '**' for path should work for all other unexistent routes, but it doesn't.

Can someone help?

-angular2 final (2.0.0)

回答1:

URL matching wont work with wildcard lazy loaded modules. I wonder what you will add in the routing inside your Lazy loaded modules.

Having said that you may try to redirect to a different route for wildcard routes like below,

{ path: 'notfound', loadChildren: 'app/notfound/notfound.module#NotFoundModule'}
{ path: '**', redirectTo: '/notfound' }

Update

you may give an empty path in Module routing so that it loads default component,

const notfoundRoutes: Routes = [
  { path: '',  component: NotFoundComponent }
];

This makes sure that when you route to a path which is not configured it goes and loads NotFound module lazily.

See this Plunker!!

Hope this helps!!



回答2:

Ok figured it out, what I did was the following.

imported the NotFound module in AppModule

@NgModule({
  imports: [
    BrowserModule,
    HttpModule,
    CoreModule.forRoot(),
    NotFoundModule,
    routing
  ],
  declarations: [
    AppComponent
  ],
  providers: [  ],
  bootstrap: [AppComponent]
})

inside the NotFound module I declared a route (not a lazy one)

const routes: Routes =  [
  { 
    path: 'notfound', 
    component: NotFoundComponent
  }
]

in the AppModule routings I added

export const routes: Routes = [
  { path: '', redirectTo: 'dashboard', pathMatch: 'full'},
  { path: 'dashboard', loadChildren: 'app/dashboard/dashboard.module#DashboardModule'},
  { path: 'buckets', loadChildren: 'app/buckets/buckets.module#BucketsModule'},
  { path: '**', redirectTo: '/notfound' } 
];

This way the NotFound module is directly imported in the app, so it does exist in the application context.

Everytime you enter a unexistent route you get routed to /notfound ;)