Creating multiple error paths in Angular 2

Asked

Viewed 156 times

0

Hello, I’m working with Angular 2(v4+), where my application has the following structure containing 2 modules that are dynamically loaded (via loadChildren):

Directory structure

app
 |-foo
 |  |- foo.module
 |  |- ... (foo components)
 |-bar 
 |  |- bar.module
 |  |- ... (bar components)

Approuting.ts

export const AppRoutes: Routes = [
    { path: '', loadChildren: './foo/foo.module#FooModule' },
    { path: 'bar', loadChildren: './bar/bar.module#BarModule' }
];

Foorouting.ts

export const FooRoutes: Routes = [
    { path: '', component: ManageComponent },
    { path: ':id', component: DetailsComponent },
    { path: 'list', component: ListComponent },
    { path: '**', component: FooErrorNotFoundComponent }
];

Barrouting.ts

export const BarRoutes: Routes = [
    { path: '', component: WorkspaceComponent },
    { path: 'view', component: ViewComponent },
    { path: 'another', component: AnotherComponent },
];

My problem is this:

  • I need each sub-module to have its own error screen, because its sub-components can change as navigation bars, etc...
  • When I use the above structure and try to access the url localhost:300/bar/view Angular is directing me to the Foo error page, meaning he’s not initially respecting the Approuting routes and going straight to Foo.
  • If I remove the Foo error page, then Angular directs me to the Bar submodule.

How can I keep the Foo module error page but forcing Angular to respect the initial App routing structure?

1 answer

0

I found the solution when I decided to read more deeply the Angular 2 documentation itself (here):

[...] The order of the Routes in the Configuration Matters and this is by design. The router uses a first-match wins Strategy when matching Routes, so more specific Routes should be placed above Less specific Routes. In the Configuration above, Routes with a Static path are Listed first, Followed by an Empty path route, that Matches the default route. The wildcard route comes last because it Matches Every URL and should be Selected only if no other Routes are Matched first. [...]

According to the specification, for what I need to work, I have to generate the routes by sorting the most complex to the simplest, then my Approuting will have its structure reversed, so:

Approuting

export const AppRoutes: Routes = [
    { path: 'bar', loadChildren: './bar/bar.module#BarModule' },
    { path: '', loadChildren: './foo/foo.module#FooModule' }
];

Doing this, even if the route does not exist, the application will first try to find in Bar an error page, so I can have 2 different error pages, and what will differentiate will be the initial routes (or '' or 'bar').

Browser other questions tagged

You are not signed in. Login or sign up in order to post.