[英]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.