Angular 11 从 URL 获取参数
Angular 11 get params from URL
我想从我的 url 中获取参数。我的路线结构为
{
path: 'customers/viewCustomer/:id',component:CommonSingleCustomerPageComponent, canActivate: [AuthGuard], data:{ permission:['Manage-Customer']},
children: [
{
path: 'detail',
component: ViewCustomerComponent, canActivate: [AuthGuard],data:{permission: ['Manage-Customer']}
},
}
但是当我尝试获取 ViewCustomerComponent 中的 :id 时,我发现它是未定义的。
我试过以下方法:
export class ViewCustomerComponent implements OnInit {
constructor(
private router: ActivatedRoute,
) { }
data: any = '';
id: any = '';
ngOnInit(): void {
this.id = this.router.snapshot.params.id
console.log(this.id)
}
}
还有,
export class ViewCustomerComponent implements OnInit {
constructor(
private router: ActivatedRoute,
) { }
data: any = '';
id: any = '';
ngOnInit(): void {
this.id = this.router.snapshot.paramMap.get('id')
console.log(this.id)
}
}
但是 none 这些作品。知道我做错了什么吗?
您想访问在父级中定义的路径路由。所以使用父对象访问子组件 ViewCustomerComponent
中的值 (:id)
this.router.parent.params
或参考这篇文章
https://ultimatecourses.com/blog/angular-parent-routing-params
我想从我的 url 中获取参数。我的路线结构为
{
path: 'customers/viewCustomer/:id',component:CommonSingleCustomerPageComponent, canActivate: [AuthGuard], data:{ permission:['Manage-Customer']},
children: [
{
path: 'detail',
component: ViewCustomerComponent, canActivate: [AuthGuard],data:{permission: ['Manage-Customer']}
},
}
但是当我尝试获取 ViewCustomerComponent 中的 :id 时,我发现它是未定义的。 我试过以下方法:
export class ViewCustomerComponent implements OnInit {
constructor(
private router: ActivatedRoute,
) { }
data: any = '';
id: any = '';
ngOnInit(): void {
this.id = this.router.snapshot.params.id
console.log(this.id)
}
}
还有,
export class ViewCustomerComponent implements OnInit {
constructor(
private router: ActivatedRoute,
) { }
data: any = '';
id: any = '';
ngOnInit(): void {
this.id = this.router.snapshot.paramMap.get('id')
console.log(this.id)
}
}
但是 none 这些作品。知道我做错了什么吗?
您想访问在父级中定义的路径路由。所以使用父对象访问子组件 ViewCustomerComponent
中的值 (:id)this.router.parent.params
或参考这篇文章 https://ultimatecourses.com/blog/angular-parent-routing-params