Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Router getCurrentNavigation always returns null

Tags:

angular

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

like image 365
Chenna Avatar asked Feb 26 '19 17:02

Chenna


3 Answers

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;
}
like image 116
Batajus Avatar answered Nov 10 '22 08:11

Batajus


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;
}
like image 22
Sivaramakrishnan Avatar answered Nov 10 '22 10:11

Sivaramakrishnan


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.

like image 1
1antares1 Avatar answered Nov 10 '22 10:11

1antares1