简体   繁体   English

访问子模块中的路由 ID

[英]Accessing route ID in child module

I am pretty new to Angular routing and am trying to access an ID from the route but it seems like no params are available.我对 Angular 路由很陌生,我正在尝试从路由访问 ID,但似乎没有可用的参数。 Here's how my routes are organized (this is imported in app.module.ts):这是我的路线的组织方式(这是在 app.module.ts 中导入的):

import {FinancePageModule} from './client-detail/finance/finance.module';
import {AuthGuard} from '../../auth/auth.guard';
import {ClientDetailPageModule} from './client-detail/client-detail.module';
import {ClientIndexPageModule} from './client-index/client-index.module';

const clientsRoutes: Routes = [
  {
    path: 'clients',
    component: ClientIndexPage,
    canActivate: [AuthGuard],
  },
  { path: 'clients/:id',
    component: ClientDetailPage,
    canActivate: [AuthGuard],
    canActivateChild: [AuthGuard],
    children: [
      {
        path: 'finance',
        component: FinancePage
      },
      {
        path: '',
        redirectTo: 'finance',
        pathMatch: 'full'
      }
    ]
  },
];

@NgModule({
  imports: [
    RouterModule.forChild(clientsRoutes),
    FinancePageModule,
    ClientIndexPageModule,
    ClientDetailPageModule,
  ],
  exports: [RouterModule]
})
export class ClientsRoutingModule { }

My FinancePageModule has no routing (which might be why I cannot access the ID) and when the FinancePage is loaded, the ID is null.我的FinancePageModule没有路由(这可能是我无法访问 ID 的原因)并且在加载FinancePage时,ID 为空。

export class FinancePage implements OnInit {

  client_id: number;

  constructor( private route: ActivatedRoute ) {
  }

  ngOnInit() {
    this.client_id = parseInt(this.route.snapshot.paramMap.get('id'));
    console.log(this.client_id) // logs NaN
  }
}

How do I modify my routing so that this variable is available in the FinancePage component?如何修改我的路由,以便此变量在FinancePage组件中可用?

In your case the id is set in the parent route so you can use this.route.parent ,在您的情况下, id设置在父路由中,因此您可以使用this.route.parent

The reason is ActivatedRoute only passes the parameters for the current component route and because the route for finance doesn't have any route parameters it didn't pass any parameter so you have to get the params for the parent route by using route.parent .原因是 ActivatedRoute 只传递当前组件路由的参数,并且因为 Finance 的路由没有任何路由参数,所以它没有传递任何参数,因此您必须使用route.parent获取父路由的route.parent

 ngOnInit() {
    this.client_id = parseInt(this.route.parent.snapshot.paramMap.get('id'));

   this.route.parent.params.forEach(
      param => console.log(param)
    )

    this.route.parent.paramMap.subscribe(params => {
      console.log(params)
    })
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM