Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 router config, prefix pathMatch does not work

From what I understand from Angular2 router documentation, the routes config default pathMatch strategy is "prefix", "prefix" pathMatch strategy means the the app router only needs to look on the start of the url and match it with the proper route.

Reference: https://angular.io/docs/js/latest/api/router/index/Routes-type-alias.html#!#matching-strategy

That been said, with the below configurations I would assume that this route should load ExampleComponent if I navigate to /abcdefg.

One problem that this is not working, am not sure what is wrong and i cant find much information about this on google or in @angular/router source code.

Thank you for your help.

const ROUTES: Routes = [
  { path: '', component: MainLayoutComponent, pathMatch: 'prefix', canActivate: [AuthGuard], children: [
    { path:'abc', pathMatch: 'prefix', component: ExampleComponent},
    { path: '', component: HomepageComponent }
  ]},
 ];


 export const ROUTING = RouterModule.forRoot(ROUTES, { useHash: false });

Update #1, Trying GĂŒnter Zöchbauer suggestion.

new router configurations are:

now /abc/defg works but not /abcdefg

{ path:'abc', pathMatch: 'prefix',
  children: [
    { path:'**', component:ExampleComponent},
  ]
}
like image 306
Anas Al Hamdan Avatar asked Oct 09 '16 15:10

Anas Al Hamdan


Video Answer


2 Answers

That would work if your path: 'abc' route had a child route with path: 'defg' or path: '**' or path: 'de' and the child route had a route with path: 'fg'.

pathMatch: 'full' means, that the whole URL path needs to match and is consumed by the route matching algorithm.

pathMatch: 'prefix' means, the first route where the path matches the start of the URL is choosen, but then the route matching algorithm is continuing searching for matching child routes where the rest of the URL matches.

like image 168
GĂŒnter Zöchbauer Avatar answered Sep 21 '22 13:09

GĂŒnter Zöchbauer


The problem is you're saying :

{ path: '', component: MainLayoutComponent, pathMatch: 'prefix'

which basically saying :

Find any url that starts with nothing ('') and simply enough, all the urls always start with nothing.

Consider this url /google

Or this url

if you run a Regex and say does these urls match to ''?, yes the do.

Unless you say the starting (^) and ending ($) bit should match too, which in that case, starting will match for both of them , but ending will only match to the empty url.

That's what they've created the full prefix , as to say , the url should exactly match .

like image 29
Milad Avatar answered Sep 21 '22 13:09

Milad