[英]Accessing route ID in child module
我对 Angular 路由很陌生,我正在尝试从路由访问 ID,但似乎没有可用的参数。 这是我的路线的组织方式(这是在 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 { }
我的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
}
}
如何修改我的路由,以便此变量在FinancePage
组件中可用?
在您的情况下, id
设置在父路由中,因此您可以使用this.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.