本文介绍了路由器getCurrentNavigation始终返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在最新版本的Angular 7.2.6中,我正在尝试在路由器本身中传递数据

In the latest version of Angular 7.2.6, I'm trying to pass data in router itself

this.router.navigate(['other'], {state: {someData: 'qwert'}}

OtherComponent文件中,this.router.getCurrentNavigation()始终返回null

In the OtherComponent file, this.router.getCurrentNavigation() always return null

Stackblitz链接

角度文档-getCurrentNavigation

角度文档-状态

推荐答案

您调用方法getCurrentNavigation为时已晚.导航已完成.

You're calling the method getCurrentNavigation too late. The navigation has finished.

您需要在构造函数内部调用getCurrentNavigation方法:

You need call the getCurrentNavigation method inside of the constructor:

constructor(private router: Router) {
    this.name = this.router.getCurrentNavigation().extras.state.example;
}

或者如果您想访问ngOnInit中的导航,则可以执行以下操作:

Or if you want to access the navigation in ngOnInit you can do following:

ngOnInit() {
    this.name = history.state.example;
}

这篇关于路由器getCurrentNavigation始终返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 15:53