有没有办法将回调函数附加到 Angular 路由模块中的路由?

Is there any way to attach a callback function to a route in an Angular routing module?

我正在 Angular 上构建一个大型应用程序,它使用带有子路由的功能模块。每个子部分都通过特定于部分的布局呈现,MVP 设置子页面的状态。例如:

/app/projects/yJEBuuOmmRv7WuVomGkb 会将项目 yJEBuuOmmRv7WuVomGkb 加载到任何子路由上的状态容器中。

我尝试过观察路由器事件,但遇到了一些具有挑战性的情况,即应用在不同的上下文(子与父)中处理不同的路由器。

我想在路由定义中执行此操作,并且想知道是否有任何方法可以将回调函数附加到可以捕获路由参数并将它们应用于状态容器的路由。

例如,类似这样的伪代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
const routes: Routes = [
  {
    path: '',
    component: PageLayoutComponent,
    children: [
      {
        path: '',
        component: PagesComponent
      },
      {
        path: 'admin/settings',
        component: PageSettingsComponent
      },
      {
        path: 'admin/publishing',
        component: PagePublishingComponent
      },
      {
        path: ':pageId',
        component: PageDetailLayoutComponent,
       
        // pseudo code!!!
        onRoute: (params => {
          StateContainer.set('page', params.pageId);
        }),
       
        children: [
          {
            path: '',
            component: PageComponent
          }
        ]
      }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class PagesRoutingModule { }

您有一些选项可以将数据添加到路由。

  • 路线中的数据属性:
  • 示例:

    1
    2
    3
    4
    5
    {
       path: 'heroes',
       component: HeroListComponent,
       data: { title: 'Heroes List'
     }

    来自angular文档:

    The data property in the third route is a place to store arbitrary
    data associated with this specific route. The data property is
    accessible within each activated route. Use it to store items such as
    page titles, breadcrumb text, and other read-only, static data. You'll
    use the resolve guard to retrieve dynamic data later in the guide.

  • 解析器
  • 示例:

    1
    2
    3
    4
    5
    {
        path: 'heroes',
        component: HeroListComponent,
        resolve: { hero: HeroResolver }
    }

    来自angular文档:

    In summary, you want to delay rendering the routed component until all
    necessary data have been fetched.

    更多信息:https://angular.io/guide/router#resolve-guard
    所以这意味着如果你调用一个为你的组件提供数据的 api 端点,你应该使用 resolver.

    也许你可以在组件的 ngOnInit 方法中调用 StateContainer.set