注意:以下内容适用于Angular 4.x
我只是使用了一个匹配函数:
import { RouterModule, UrlSegment, UrlSegmentGroup, Route } from '@angular/router';
function CaseInsensitiveMatcher(url: string) {
url = url.toLowerCase();
return function(
segments: UrlSegment[],
segmentGroup: UrlSegmentGroup,
route: Route
) {
let matchSegments = url.split('/');
if (
matchSegments.length > segments.length ||
(matchSegments.length !== segments.length && route.pathMatch === 'full')
) {
return null;
}
let consumed: UrlSegment[] = [];
let posParams: {[name: string]: UrlSegment} = {};
for (let index = 0; index < segments.length; ++index) {
let segment = segments[index].toString().toLowerCase();
let matchSegment = matchSegments[index];
if (matchSegment.startsWith(':')) {
posParams[matchSegment.slice(1)] = segments[index];
consumed.push(segments[index]);
}
else if (segment === matchSegment) {
consumed.push(segments[index]);
}
else {
return null;
}
}
return { consumed, posParams };
}
}
使用:
@NgModule({
imports: [
...
RouterModule.forRoot([
{ matcher: CaseInsensitiveMatcher('user/:id'), component: ProfileComponent },
])
],
declarations: [
...
],
bootstrap: [
AppComponent
]
})
编辑:我刚刚发现,为了使用AoT编译,@NgModule部分应该如下所示:
export function profileMatch() {
return CaseInsensitiveMatcher('user/:id').apply(this, arguments);
}
@NgModule({
imports: [
...
RouterModule.forRoot([
{ matcher: profileMatch, component: ProfileComponent },
])
],
declarations: [
...
],
bootstrap: [
AppComponent
]
})