Router getCurrentNavigation always returns null

2020-05-20 02:19发布

问题:

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'}}

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

Stackblitz Link

Angular Docs - getCurrentNavigation

Angular Docs - state

回答1:

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

You need call the getCurrentNavigation method inside of the constructor:

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

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

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


回答2:

change the code like this because after constructor() only the ngOnInit() gets called so the value is getting null

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


回答3:

work for me Ionic 4

  • this.router.url => /app/menu/etc // current position


标签: angular