Angular routes: prefix matching

Viewed 1166

I am reading documentation on the Angular routing and created a simple test:

const routes: Route[] = 
[
    { path: '', redirectTo: '/home', pathMatch: 'full' },
    { path: 'home', pathMatch: 'prefix', component: HomeComponent },
//  { path: '**', component: PageNotFoundComponent },
];

To my understanding the path like "/home/12345" should match the second route. The path is a prefix for this URL... But this does on happen:

enter image description here

The behavior is like it has not mapped any component on the router outlet. The big header on the page comes from the upper component. If I uncomment the third route ("**"), this path would go to the PageNotFoundComponent.

What am I doing wrong or where is my misunderstanding? Why my 2-path variant is not working?

1 Answers

This is not quite what prefix means though.

In most cases you just need the default pathMatch prefix. It means that the angular routing finds the first router that matches the URL and then goes further and looks for any children that might match the route (and in your case there are none).

You don't really need pathMatch 'full' in cases other than when you're redirecting empty paths (which is what they show you in the example). I don't think there are other cases when it's useful (but maybe someone can comment).

You see this error correctly, because there is no such defined route. If you want a variable after 'home', you have to define it as 'home/:variableName'.

From the docs:

Technically, pathMatch = 'full' results in a route hit when the remaining, unmatched segments of the URL match ''. In this example, the redirect is in a top level route so the remaining URL and the entire URL are the same thing.

The other possible pathMatch value is 'prefix' which tells the router to match the redirect route when the remaining URL begins with the redirect route's prefix path. This doesn't apply to this sample app because if the pathMatch value were 'prefix', every URL would match ''.

Related