Router getCurrentNavigation always returns null

Angular

Angular Problem Overview


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

Angular Solutions


Solution 1 - Angular

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.someData;
}

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

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

Solution 2 - Angular

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

Solution 3 - Angular

This happened to me because there was a promise (asynchronous process) in the Event of the NavigationEnd, before consuming the getCurrentNavigation().extras().state of the current state.

I moved the promise after and voila! It managed to get the data without first being cleaned.

Solution 4 - Angular

For spec (tests), the getCurrentNavigation() on constructor don´t work, you have to use the history at ngOnInit() and mock values at history, for example:

beforeEach(() => {
    window.history.pushState({name: 'MyName', id: 1}, '', '');
}

Now your component can use this values on ngOnInit() and use on spec.:

ngOnInit(): void {
    console.log(history.state.name);
}

Solution 5 - Angular

work for me Ionic 4

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChennaView Question on Stackoverflow
Solution 1 - AngularBatajusView Answer on Stackoverflow
Solution 2 - AngularSivaramakrishnanView Answer on Stackoverflow
Solution 3 - Angular1antares1View Answer on Stackoverflow
Solution 4 - AngularFabricio LeiteView Answer on Stackoverflow
Solution 5 - AngularIvancho DiazView Answer on Stackoverflow