Ferie
Ferie

Reputation: 1436

Angular 5/6 router: redirect a non existing route that has been defined with parameters

Let's suppose that I have a project that has these routes:

... /* Other routes */
{
    path: 'main/:category',
    component: CategoryComponent,'
},
{
    path: '404',
    component: PageNotFoundComponent
},
{
    path: '**',
    component: PageNotFoundComponent
}

Now let's suppose that I am surfing to /main/category1 the route is working correctly.

But, if I am surfing to a route like this /main/jshfsahgflkhghfdsiughisdfg that is obviously a wrong route, I would like that this is redirected to the 404 page.

How can I do this?

Upvotes: 5

Views: 4388

Answers (1)

Reactgular
Reactgular

Reputation: 54741

But, if I am surfing to a route like this /main/jshfsahgflkhghfdsiughisdfg that is obviously a wrong route, I would like that this is redirected to the 404 page.

There is no pattern matching for route parameters in Angular (I wish there was). There isn't really an easy solution, but I've tried both of the following methods.

Custom URL Matcher

Write a function that handles the route matching for that outlet. You can then use a pattern for the parameters that you want.

https://angular.io/api/router/UrlMatcher

Make 404 an application state

The problem with doing just this route:

{path: '**', component: PageNotFoundComponent}

Is that the page not found message is only shown for mismatched routes. It doesn't handle cases like invalid parameters, failure to load resolvers or failure to lazy load data.

Instead, display the 404 message in the application's main component.

app.component.html:

<div *ngIf="notFound">Page is not found</div>
<router-outlet *ngIf="!notFound"></router-outlet>

Add logic to your template to display the 404 error and remove the <router-outlet> when the error is shown.

notfound.service.ts:

Create a service that will emit if the main component should display the 404 error message.

 @Injectable()
 export class NotFoundSerivce {
      public notFound = new Subject<boolean>();
 }

You can now add logic to your routers in the components to check for the parameter patterns or valid state. If the logic says it should be a 404, then use the NotFoundService to trigger the 404 error.

page-not-found.component.ts:

Update your current 404 component to trigger the NotFoundService.

Upvotes: 5

Related Questions