Brandon Dixon
Brandon Dixon

Reputation: 1134

Angular: How to Retrieve the Target Url when Redirect to 404 Page

In my Angular application, I am handling 404 routing in this manner:

{
    path: '404',
    loadChildren: () =>
        import('../pages/404-pg/404-pg.module').then(
            (m) => m.FourZeroFourPgModule
        ),
},
{
    path: '**',
    redirectTo: '/404',
}

The redirect works fine, but I've noticed a few 404 logs in my page navigation logs on my deployed website and am currently not logging the url which the user visited which caused the 404 redirect. How can I use the router to determine the "original" route?

For example, if I type: localhost:4200/bad-url in the browser, how can I get the "/bad-url" path using the Router object (or ActivatedRoute, etc)?

Upvotes: 2

Views: 984

Answers (1)

Adrian Sawicki
Adrian Sawicki

Reputation: 708

You could create an interceptor to handle such cases.

For example,

WHEN you type "localhost:4200/bad-url"

THEN in the interceptor just before redirect you have access to the currently typed URL (this.router.url)

AND you can save it in storage as "last_route_from_error" or something like this

THEN user is redirected to 404 page

AND you have the whole URL saved in storage

Upvotes: 0

Related Questions