路由器getCurrentNavigation始终返回null

Che*_*nna 18 angular

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

this.router.navigate(['other'], {state: {someData: 'qwert'}}
Run Code Online (Sandbox Code Playgroud)

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

Stackblitz链接

Angular Docs-getCurrentNavigation

Angular Docs-状态

Bat*_*jus 35

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

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

constructor(private router: Router) {
    this.name = this.router.getCurrentNavigation().extras.state.example;
}
Run Code Online (Sandbox Code Playgroud)

或者,如果要访问导航,则ngOnInit可以执行以下操作:

ngOnInit() {
    this.name = history.state.example;
}
Run Code Online (Sandbox Code Playgroud)

  • 也适用于ionic4`ionViewDidEnter()` (2认同)
  • 有关 Angular 15+ 的问题,请参阅 @Matthieu Riegler 答案 (2认同)

Mat*_*ler 22

自 Angular 16 起,将lastSuccessfulNavigation替换 v15 中引入的重大更改,其中getCurrentNavigation可能会返回null


v16 之前的答案:

从 Angular 15 开始,this.router.getCurrentNavigation()可能会返回 null,因为组件是在导航后实例化的。

Location另一种方法是从(来自 的那个@angular/common)访问状态

  import { Location } from '@angular/common';

  constructor(private location: Location) {
    location.getState() // do what you want 
  }
Run Code Online (Sandbox Code Playgroud)


Siv*_*nan 6

像这样更改代码,因为constructor()只有在ngOnInit()被调用之后,值才会变为空

constructor(private router: Router) {
   this.name = this.router.getCurrentNavigation().extras.state.example;
}
Run Code Online (Sandbox Code Playgroud)