angular - 有什么方法可以将回调函数附加到 Angular 路由模块中的路由吗?

标签 angular angular-router

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

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

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

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

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

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. route 的数据属性:

示例:

{
   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.

  • 解析器
  • 示例:

    {
        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 端点,则应该使用解析器。

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

    关于angular - 有什么方法可以将回调函数附加到 Angular 路由模块中的路由吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54223751/

    相关文章:

    angular - FormArray 返回 null?

    angular - ngrx 在组件(与路由关联)init 上调度操作

    angular - 在路由中将对象作为参数传递返回 [Object object]

    css - 在 Angular 5 的路由器导出中仅呈现组件模板

    javascript - Angular 路由器中全局可用的 url 参数

    angular - 子路由上的 RouterLinkActive 全部为 false

    java - 如何使用 Spring Security + Angular 登录/认证

    html - Bootstrap 4 : external navbar content responsiveness issue

    javascript - 使用 Angular 2/4 多选元素

    Angular RouteReuseStrategy 滚动位置保持