我有一个带有以下路由的 ProfileModule
:
// profile-routing.module
const routes: Routes = [
{
path: ':id',
component: ProfilePageComponent,
children: [
{
path: '',
redirectTo: 'feed',
pathMatch: 'full'
},
{
path: 'feed',
component: NewsFeedComponent
},
{
path: 'gallery',
component: MediasGalleryComponent
}
]
}
];
它的工作原理如下:
ProfilePageComponent
获取路由参数中的配置文件 ID 并将其发送到ProfilePageService
NewsFeedComponent
和MediasGalleryComponent
从ProfilePageService
接收配置文件 ID
现在,这两个页面已被移动到两个单独的模块中(分别为 NewsModule
和 MediasModule
),我想成为 延迟加载。我不能再使用 ProfilePageService 了。我想出了这个解决方案:
// profile-routing.module
const routes: Routes = [
{
path: ':id',
component: ProfilePageComponent,
children: [
{
path: '',
redirectTo: 'news/:id/feed', // same as the parent ID
pathMatch: 'full'
},
{
path: 'news',
loadChildren: () => import('./news/news.module').then(m => m.NewsModule)
},
{
path: 'medias',
loadChildren: () => import('./medias/medias.module').then(m => m.MediasModule)
}
]
}
];
// news-routing.module
const routes: Routes = [{
path: ':profileId/feed',
component: NewsFeedComponent
}];
// medias-routing.module
const routes: Routes = [{
path: ':profileId/gallery',
component: MediasGalleryComponent
}];
此解决方案不起作用,因为我无法从父路由获取配置文件 ID 参数。我怎样才能避免这个问题?
此外,我不喜欢配置文件 ID 在 URL 中重复的事实。 Angular 做事的方式是什么?
最佳答案
这是因为子模块只将其模块的路径视为其根路径,不包括 :id
。您可以在应用程序根目录中提供一个 sharedService 并在路由更改时读取 id。然后您可以从子模块中读取该 ID。
@Injectable()
export class RouterStateService {
params$: Observable<Params>;
}
然后在您的应用程序组件中您可以执行
@Component(...)
export class AppComponent {
constructor(private activatedRoute: ActivatedRoute, private routerState: RouterStateService) {}
ngOnInit() {
this.routerState.params$ = this.activatedRoute.params;
}
}
在您的子组件/模块中,您可以将其用作
@Component(...)
export class WhatEverComponent {
constructor(private routerState: RouterStateService) {}
ngOnInit() {
this.routerState.params$.subscribe(console.log);
}
}
一如既往:如果您不再需要该流,请不要忘记取消订阅。
关于带有父路由参数的 Angular 延迟加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57305591/