Angular 14中访问路由extra.state数据及解决类型报错
Angular 14 路由State传递对象后的访问与类型错误解决
你遇到的编译错误是因为this.router.getCurrentNavigation()?.extras.state可能返回undefined,而你的this.product是Product类型(非可选),TypeScript不允许将undefined赋值给非可选类型的变量。以下是几种解决方法:
方法一:类型断言+空值处理
通过类型断言明确告诉TypeScript返回的state是Product类型,同时处理未获取到数据的场景:
constructor( private router: Router, private route: ActivatedRoute, ... ) { const navigation = this.router.getCurrentNavigation(); if (navigation?.extras?.state) { this.product = navigation.extras.state as Product; } else { // 根据业务需求处理空值,比如赋值默认对象或跳转至错误页 this.product = {} as Product; // this.router.navigate(['/some-path']); } }
方法二:将变量声明为可选类型
如果业务允许product为undefined,可以直接修改变量的类型定义:
// 组件内变量声明 product: Product | undefined; constructor( private router: Router, private route: ActivatedRoute, ... ) { this.product = this.router.getCurrentNavigation()?.extras?.state as Product; }
补充:组件初始化后访问路由State
如果是在ngOnInit钩子中访问(此时导航已完成,getCurrentNavigation()会返回null),需要从window.history.state获取:
ngOnInit(): void { this.product = window.history.state as Product; }
内容的提问来源于stack exchange,提问作者Dave
相关产品推荐
相关产品推荐

