我在应用程序中使用命名路由器在其中一个共享模块中实现路由。
以下是 AppRoutingModule (root) 中的配置:
const routes: Routes = [
{
path: '',
children: [
{
path: 'home',
component: HomeDetailsComponent,
},
{
path: 'call',
component: CallDetailsComponent
},
]
}
];
然后,当用户导航到第一个路径(即"/home")时,该模块有一个单独的路由模块,它具有以下配置:
const curriculumRoutes: Routes = [
{
path: 'home',
component: HomeDetailsComponent,
children: [
{
path: ':id',
component: RoomDetailsComponent,
outlet: 'chapter',
}
]
},
];
对于第一个根配置,我使用主插座来渲染组件,对于第二个配置,我使用命名路由器"章"。我从主路由器插座获得的 URL 如下:
http://localhost:3000/#/home
但是有了进一步命名的路由器插座,它是这样的:
http://localhost:3000/#/home/(chapter:2)
如何为命名路由器插座提供这样的 URL:
http://localhost:3000/#/home/chapter/2
我做了一个解决方案,希望它可以帮助其他人。
UrlSerializer 的解决方案重写。
在这个例子中,我们像这样翻译成 aux:
parse:/instruments/ukulele=>/instruments/(instruments:ukulele)
序列化:/instruments/(instruments:ukulele) =>/instruments/ukulele
这样最终用户只能看到漂亮的网址:
/乐器/尤克里里
UrlSerializer 的实现:
//app.rounting.ts
const routes: Routes = [
/*...*/
{
path: 'instruments', component: InstrumentsComponent,
children: [
{
path: 'ukulele',
component: UkuleleComponent,
outlet: 'instruments'
}
]
}
];
//app.module.ts
@NgModule({
/*...*/
declarations: [
/*...*/
InstrumentsComponent,
UkuleleComponent
],
/*...*/
providers: [
{
provide: UrlSerializer,
useClass: StandardUrlSerializer
}
],
/*...*/
})
//app.contants.ts
export let appContants = {
outlets: ['instruments']
};
// StandardUrlSerializer.ts
import { DefaultUrlSerializer, UrlSerializer, UrlTree } from '@angular/router';
import { appContants } from '../app.constants';
export class StandardUrlSerializer implements UrlSerializer {
private _defaultUrlSerializer: DefaultUrlSerializer = new DefaultUrlSerializer();
parse(url: string): UrlTree {
appContants.outlets.forEach(outletName => {
const reg = new RegExp('/(' + outletName + ')/([^/]*)');
url = url.replace(reg, '$1/($1:$2)' );
});
return this._defaultUrlSerializer.parse(url);
}
serialize(tree: UrlTree): string {
let url = this._defaultUrlSerializer.serialize(tree);
appContants.outlets.forEach(outletName => {
const reg = new RegExp('\(' + outletName + ':([^/]*)\)');
url = url.replace(reg, '$1');
});
return url;
}
}
<!-- app.component.html -->
<!-- ... -->
<a routerLinkActive="active" routerLink="/instruments">Instruments</a>
<router-outlet></router-outlet>
<!-- ... -->
<!-- instruments.component.html -->
<!-- ... sub menu etc.. -->
<a class="nav-item nav-link" routerLinkActive="active" [routerLink]="[{ outlets: { instruments: ['ukulele'] } }]">Ukulele</a>
<router-outlet name="instruments"></router-outlet>
<!-- ... -->
<!-- ukulele.component.html -->
<p>ukulele works!</p>
您可以提供自定义 URL 序列化程序
https://angular.io/docs/ts/latest/api/router/index/UrlSerializer-class.html