在 Angular 14 中,我如何访问传递给路由“extra.state”的数据?

问题描述 投票:0回答:1

我正在使用 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'.
angular routes state router angular14
1个回答
0
投票

仅从代码片段很难回答,但这对我有用:

constructor(private router: Router) {
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationEnd && event?.url === '/start') {
        this.product = this.router.getCurrentNavigation()?.extras.state;
      }
    });
  }
© www.soinside.com 2019 - 2024. All rights reserved.