简体   繁体   中英

Angular 2/4/5 Catch routerLink exception

I'm trying to catch routing exceptions in my app. Basically there are 3 ways a user can navigate:

  1. Typing the address - catching that is easy just { path: '**', redirectTo: 'errorPage'} in the route config.
  2. The code called router.navigate(['pageName']) - catching that is easy too: .then(res => res, error => { //service to log error to server router.navigate(['errorPage']); });
  3. Clicking an HTML element that has [routerLink]="somePath" attribute.

It's the third one that I don't know how to catch.
Presumably such an error could occur if the module didn't load for some reason. I need to be able to handle that (and other unforeseen events) gracefully.

TO CLARIFY
The wildcard definition works for router problems, in most cases. But here's the thing, what if there is a route defined earlier in the configuration, but it leads to a module that can't be found! (I actually had this error in develop, which is why I am aware that it can happen, we're using lazy loading, and it happened that with some network problems a required module didn't load). The router finds a route, and tries to resolve it, but can't because the module, for whatever reason, did not load. The wildcard definition doesn't help here, because the router found a path but can't reach it. So it throws an error, which I'm trying to catch. Because for some reason router errors choke the whole app.

Why not create fallback path in routing module?

const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: '**', component: NotFoundComponent },
];

When user enter not existing url will be redirected to NotFoundComponent.

This { path: '**', redirectTo: 'errorPage'} is what is called the wildcard route definition, which Angular official doc defines as:

The router will select this route if the requested URL doesn't match any paths for routes defined earlier in the configuration. This is useful for displaying a "404 - Not Found" page or redirecting to another route.

So this should work for any case when the requested route doesn't match any of the defined routes (doesn't matter if it was typed or set). Check if the routerLink definition is correct because the definition for it is without the brackets: <a routerLink="/crisis-center" routerLinkActive="active">Crisis Center</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM