I've added a NotFoundComponent to my angular app, but I'm noticing some strange behavior. Here is my code in app-routing.module.ts:
export const routes: Routes = [
{ path: 'instructions', component: InstructionsComponent },
{ path: 'foo', component: FooComponent, canDeactivate: [DeactivateGuard] },
{ path: 'bar', component: BarComponent },
{ path: '', redirectTo: '/instructions', pathMatch: 'full' },
{ path: '**', component: NotFoundComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes, { relativeLinkResolution: 'legacy' })],
exports: [RouterModule]
})
export class AppRoutingModule { }
If I search for "myapp/foo", I get the FooComponent (which is correct). If I search for "myapp/fooTest", I get the NotFoundComponent (which is correct).
If I search for "myapp/foo/test", I get a blank screen (which is incorrect). And this is my question. Why isn't it routing to the NotFoundComponent if I have a "/" in my incorrect search?
CodePudding user response:
It happens because you haven't set up any pathMatch
for your foo
path. This way you have default pathMatch: prefix
which means that any URL starting with foo
will match this route.
fooTest
is not considered to match this rule because it looks up for paths equal to foo
or started with foo/
(so it matches all children of foo
)
If you want to redirect /foo/test
to NotFoundComponent
, then set pathMatch: full
on foo
path
CodePudding user response:
Add the following path definition in your routes array.
This will match any segment past the "foo" prefix in your URL then redirect it to your NotFoundComponent component:
{
path: 'foo',
children: [
{
path: ':anyother',
component: NotFoundComponent
}
],
},
The \foo route itself will route to the FooComponent.
The :anyother path segment will match any value.
So, the above will route as follows:
/foo will route to FooComponent.
/foo/test will route to NotFoundComponent.