如何从无组件路由的子级传递路由数据

时间:2021-06-30 22:51:43

标签: angular typescript

我正在尝试访问我的动画路由配置的 data 属性:

const routes: Routes = [
  // ... other routes
  {
    path: '',
    outlet: 'calendar',
    data: { animation : 'I can access this' },  // I don't need this
    children: [
      {
        path: '',
        redirectTo: 'month',
        pathMatch: 'full',
      },
      {
        path: 'day',
        data: { animation : 'But not this' },   // This is what I want
        loadChildren: () => import(...),
      },
      {
        path: 'month',
        data: { animation : 'Or this' },        // This is what I want
        loadChildren: () => import(...),
      }
    ]
  }
]

具体来说,我正在尝试按照 Angular Doc 的 Route transition animations guide 访问它:

html

<div [@animate]="prepareAnimation(o)">
  <router-outlet #o="outlet" name="calendar"></router-outlet>
</div>

组件

prepareAnimation(outlet: RouterOutlet): string {
  console.log(outlet.activatedRouteData.animation)
  return outlet.activatedRouteData.animation
}

这总是 console.log() 的“I can access this”,但我需要获取与 daymonth 路线关联的数据值。

有没有办法做到这一点?

附言我不想展平路由,因为它会不受欢迎地改变路由结构

1 个答案:

答案 0 :(得分:0)

要访问路由配置的 data 属性,以下代码可能对您有所帮助:

constructor(private route: ActivatedRoute) {
  this.route.url.subscribe(() => {
    console.log(this.route.snapshot.firstChild.data);
   });
}