Angular无法获取路由的@inputData - getCurrentNavigation()方法返回null值。
创始人
2024-10-30 01:00:54
0

在Angular中,getCurrentNavigation()方法用于获取当前路由的导航状态。然而,在某些情况下,该方法可能返回null值,这可能是由于异步导航或刷新页面等原因造成的。以下是解决此问题的一种常见方法:

  1. 使用订阅路由事件的方式获取当前导航信息:
import { Router, NavigationEnd } from '@angular/router';

export class YourComponent implements OnInit {
  constructor(private router: Router) {}

  ngOnInit() {
    this.router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        const navigation = this.router.getCurrentNavigation();
        if (navigation) {
          const data = navigation.extras.state;
          // 使用获取到的data进行后续操作
        }
      }
    });
  }
}

在上面的代码中,我们订阅了路由事件,并在每次导航结束时检查getCurrentNavigation()方法的返回值。如果返回值不为null,我们可以从导航对象的extras属性中获取数据。

  1. 使用ngOnInit()钩子函数获取数据:
import { Router, ActivatedRoute } from '@angular/router';

export class YourComponent implements OnInit {
  constructor(private router: Router, private route: ActivatedRoute) {}

  ngOnInit() {
    const navigation = this.router.getCurrentNavigation();
    const data = navigation?.extras?.state;
    // 使用获取到的data进行后续操作
  }
}

在上面的代码中,我们通过注入ActivatedRoute来获取当前路由的导航信息。然后,我们可以使用getCurrentNavigation()方法来获取数据。

请注意,在使用以上方法时,确保在路由的导航结束之后再使用getCurrentNavigation()方法获取数据,以避免获取到null值。

相关内容

热门资讯

透视苹果版!aapoker辅助... 透视苹果版!aapoker辅助插件工具(透视)透视软件(本来存在有挂);亲,关键说明,aapoker...
透视数据!aapoker公共底... 透视数据!aapoker公共底牌(透视)透视软件(本来是有挂)1、完成aapoker公共底牌透视辅助...
透视ai!aapoker俱乐部... 透视ai!aapoker俱乐部靠谱吗(透视)辅助插件工具(真是真的有挂)1、这是跨平台的aapoke...
透视讲解!aapoker怎么控... 透视讲解!aapoker怎么控制牌(透视)透视脚本(一贯是真的有挂);1、透视讲解!aapoker怎...
辅助透视!aapoker免费透... 辅助透视!aapoker免费透视脚本(透视)透视脚本(总是存在有挂)1、每一步都需要思考,不同水平的...
透视免费!aapoker插件(... 透视免费!aapoker插件(透视)插件(果然是有挂)1、在aapoker插件ai机器人技巧中,中转...
透视插件!aapoker怎么选... 透视插件!aapoker怎么选牌(透视)免费透视脚本(总是是有挂);1、aapoker怎么选牌ai辅...
透视ai代打!aapoker能... 透视ai代打!aapoker能控制牌吗(透视)透视方法(本来存在有挂);1、下载好aapoker能控...
透视黑科技!aapoker怎么... 透视黑科技!aapoker怎么设置抽水(透视)ai插件(其实真的有挂);1、下载好aapoker怎么...
透视线上!aapoker辅助工... 透视线上!aapoker辅助工具安全吗(透视)免费透视脚本(总是真的是有挂);1、aapoker辅助...