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

标签 angular typescript angular2-routing

我有一个带有以下路由的 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 参数。我怎样才能避免这个问题?

此外,我不喜欢配置文件 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/

相关文章:

javascript - this.router 在 AngularJS 2 中未定义

laravel - Angular 2 - 请求的资源上不存在 'Access-Control-Allow-Origin' header

javascript - karma : Cannot read property * of undefined

c# - SpreadJS 在基于 Webpack 的 Angular 应用程序中不起作用

javascript - 如果为空则不显示任何内容 (JS)

javascript - sendKeys(index) 中值的 Protractor 循环

javascript - 如果路径不存在,Angular 2 如何重定向到 404 或其他路径

Angular2 RC 和动态路由

Angular2 - 除非单击,否则不会显示更改检测

typescript - 从联合类型 typescript 生成字符串数组