Angular 带有父路由参数的延迟加载

Angular lazy load with parent route parameter

我有一个 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
      }
    ]
  }
];

它的工作原理如下:

  1. ProfilePageComponent 获取路由参数中的配置文件 ID 并将其发送到 ProfilePageService
  2. NewsFeedComponentMediasGalleryComponentProfilePageService
  3. 接收配置文件 ID

现在,这两个页面已经被移动到两个单独的模块(分别是NewsModuleMediasModule),我想成为在此路由中延迟加载。我不能再使用 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 参数。我怎样才能避免这个问题?

此外,我不喜欢 URL 中的配置文件 ID 重复这一事实。 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;
  }
}

并且在您的 child-component/module 中,您可以将其用作

@Component(...)
export class WhatEverComponent {
  constructor(private routerState: RouterStateService) {}

  ngOnInit() {
    this.routerState.params$.subscribe(console.log);
  }
}

一如既往:如果您不再需要该流,请不要忘记退订。