How to use redirectTo
in the case of child routing with a parameter in angular2. my routing structure like this
const appRoutes: Routes = [
{ path: '', redirectTo : '/home', pathMatch: 'full'},
{ path: 'home', component: HomeComponent},
{ path: 'xyz/:id', component: XYZ },
{
path: 'abc/:id', component: ABC,
children: [
{ path: '', redirectTo : 'def', pathMatch: 'prefix' },
{ path: 'def/:id', component: DEF }
]
}
]
But it's not working
also, what is pathMatch
in routing ?
Looking for your sample code, if paths 'abs/:id' and 'def/:id' use the same parameter (:id), the solution that I use was to forget the parameter in child route configuration and in its component get from its parent route:
const appRoutes: Routes = [
{
path: ':id',
component: SimulatorComponent,
children: [
{
path: 'home',
component: HomeComponent
}
]
}
];
In HomeComponent, then you catch the id from parent route:
export class HomeComponent implements OnInit {
protected id: number;
constructor(protected route: ActivatedRoute) {
}
ngOnInit() {
this.route.parent.params.subscribe(params => this.id = +params['id']);
}
}
You should redirect to home
(without the slash), since your redirectTo
value needs to match a given path
, not an arbitrary url.
For details about the pathMatch
attribute, see the section in Angular2's Routing & Navigation docs.
pathMatch = 'full' results in a route hit when the remaining, unmatched segments of the URL match is the prefix path
pathMatch = 'prefix' tells the router to match the redirect route when the remaining URL begins with the redirect route's prefix path.
Ref: https://angular.io/docs/ts/latest/guide/router.html#!#redirect
So let's take a look at your example:
const appRoutes: Routes = [
{ path: '', redirectTo : '/home', pathMatch: 'full'},
{ path: 'home', component: HomeComponent},
{ path: 'xyz/:id', component: XYZ },
{
path: 'abc/:id', component: ABC,
children: [
{ path: '', redirectTo : 'def', pathMatch: 'prefix' }, //error
{ path: 'def/:id', component: DEF }
]
}
]
Error line means that if something like abc/1 + ''
(which is abc/1
) is entered, redirectTo = 'def'
(full path = 'abc/:id/def'
) which doesn't exist.
With pathMatch = prefix
if you enter anything after abc/1
it will still try to redirectTo = 'def'
(eg abc/1/longesturl
) because after abc/1 + ''
this ''
matches any url because every url after 1
will have an empty string in it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.