我在我的应用程序中使用命名路由器在其中一个共享模块中实现路由。
这是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',
}
]
},
];
对于第一个根配置,我使用主插座来渲染组件,对于第二个配置,我使用的是命名路由器' chapter'。 我从主路由器插座获取的URL如下:
http://localhost:3000/#/home
但是进一步命名路由器插座,就像这样:
http://localhost:3000/#/home/(chapter:2)
如何为指定的路由器插座提供这样的URL:
http://localhost:3000/#/home/chapter/2
答案 0 :(得分:4)
答案 1 :(得分:3)
我提出了一个解决方案,希望它可以帮助其他人。
UrlSerializer的解决方案覆盖。
在此示例中,我们将翻译成aux:
解析:/ instruments / ukulele => / instruments /(instruments:夏威夷四弦琴)
序列化:/ instruments /(instruments:ukulele)=> / instruments / ukulele
这样最终用户只能看到漂亮的网址:
/ instruments /尤克里里琴
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>