我正在使用 Angular 14。我想将一个对象传递到我的路线以便可以访问它,所以我尝试了
this.router.navigate(['start'], { state: product, relativeTo: this.route });
我如何随后访问这些数据?在我的构造函数中,我尝试了这个
constructor(
private router: Router,
private route: ActivatedRoute,
...
) {
...
if (this.router.getCurrentNavigation()?.extras?.state) {
this.product = this.router.getCurrentNavigation()?.extras.state;
}
但这会导致编译错误
Type 'undefined' is not assignable to type 'Product'.
仅从代码片段很难回答,但这对我有用:
constructor(private router: Router) {
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd && event?.url === '/start') {
this.product = this.router.getCurrentNavigation()?.extras.state;
}
});
}