在Angular中,使用ActivatedRoute来获取路由参数是非常常见的。如果你发现ActivatedRoute无法获取参数,可能有以下几种原因和解决方法:
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.params.subscribe(params => {
// 在这里使用params对象获取参数
let id = params['id'];
console.log(id);
});
}
const routes: Routes = [
{ path: 'example/:id', component: ExampleComponent }
];
在上述示例中,参数名称是:id,你可以使用相同的名称来访问参数。
this.router.navigate(['/example', 1]); // 1是参数的值
在上述示例中,1将作为参数传递给ExampleComponent。
如果你仍然遇到问题,可以检查浏览器的开发者工具中的控制台输出,看看是否有任何错误消息或警告信息。