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插件下载(透视)真是有脚本神器(哔哩哔哩)透视技...
透视大纲!hhpoker必备开... 透视大纲!hhpoker必备开挂,hhpoker作必弊码怎么用(透视)原来是有脚本教程(哔哩哔哩)1...
透视指南!aapoker如何设... 透视指南!aapoker如何设置胜率,aa poker辅助(透视)一贯真的有脚本脚本(哔哩哔哩)1、...
透视绝活儿!wpk俱乐部有没有... 透视绝活儿!wpk俱乐部有没有辅助,wpk有辅助器吗(透视)原来存在有透视神器(哔哩哔哩)wpk俱乐...
透视方式!wpk是真的还是假的... 透视方式!wpk是真的还是假的,wpk俱乐部有没有辅助(透视)真是有透视技巧(哔哩哔哩)1、用户打开...
透视学习!wepoker私人局... 透视学习!wepoker私人局规律,wepoker插件程序激活码(透视)果然有透视方法(哔哩哔哩)1...
透视办法!wepoker插件功... 透视办法!wepoker插件功能辅助器,wepoker免费透视脚本(透视)原来是真的透视方法(哔哩哔...
透视教材!aapoker怎么提... 透视教材!aapoker怎么提高中牌率,aapoker能控制牌吗(透视)确实真的有透视插件(哔哩哔哩...
透视办法!wpk模拟器多开,w... 透视办法!wpk模拟器多开,wpk安卓下载辅助(透视)确实有透视软件(哔哩哔哩)1、每一步都需要思考...