How to create multiple error paths in Angular 2

0
Hello, I'm working with angular 2 (v4 +), where my application has the following structure containing 2 modules that are loaded dynamically (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 subcomponents can change like 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, that is, it is not initially respecting the AppRouting routes and going straight to Foo. >
  • If I remove the Foo error page, then yes the Angular directs me to the Bar sub-module.

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

    
asked by anonymous 22.08.2017 / 14:27

1 answer

0

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

  

[...] The order of the routes in the configuration matters and this is by design. The router uses first-match wins strategy when matching routes, so more specific routes should be placed above less specific routes. In the above configuration, 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 other routes are matched first. [...]

As the specification, so that what I need to work, I have to generate the routes with the ordering of the most complex to the simplest, so my AppRouting will have its structure reversed, like this:

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 attempt to find an error page in Bar, so I can have 2 different error pages, and what will differentiate will be the initial routes (or '' or '' bar ' ).

    
22.08.2017 / 14:44