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

Loh*_*eek 3 typescript angular2-routing angular

我有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
      }
    ]
  }
];
Run Code Online (Sandbox Code Playgroud)

它的工作原理如下:

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

现在,这两个页面已移入两个单独的模块(分别为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
}];
Run Code Online (Sandbox Code Playgroud)

此解决方案不起作用,因为我无法从父路由获取配置文件 ID 参数。我怎样才能避免这个问题?

此外,我不喜欢在 URL 中重复配置文件 ID 的事实。Angular 做事的方式是什么?

ngf*_*ixl 7

这是因为子模块仅将其模块的路径视为其根路径,其中不包括:id. 您可以在应用程序根目录中提供一个 sharedService 并读取路由更改时的 id。然后您可以从子模块中读取该 ID。

@Injectable()
export const RouterStateService {
  params$: Observable<Params>;
}
Run Code Online (Sandbox Code Playgroud)

在您的应用程序组件中,您可以执行以下操作

@Component(...)
export const AppComponent {
  constructor(private activatedRoute: ActivatedRoute, private routerState: RouterStateService) {}

  ngOnInit() {
    this.routerState.params$ = this.activatedRoute.params;
  }
}
Run Code Online (Sandbox Code Playgroud)

在您的子组件/模块中,您可以将其用作

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

  ngOnInit() {
    this.routerState.params$.subscribe(console.log);
  }
}
Run Code Online (Sandbox Code Playgroud)

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