0

i want to pass some data, when changing the view with navigateByUrl like

this.router.navigateByUrl(url, {state: {hello: "world"}});

In the next view i want to simply log the hello attribute like

constructor(public router: Router) { }

  ngOnInit(): void {
    console.log(this.router.getCurrentNavigation().extras.state.hello)
  }

When I now do it this way, i get an error:

ERROR TypeError: Cannot read property 'extras' of null
    at ProfileContactViewComponent.ngOnInit

Am i doing this correctly or is there a better way to pass the data between the views? Thanks for your help.

3 Answers 3

2

Try like this

Send :

this.router.navigate([url], { state: { hello: 'world' } });

Recieve:

constructor(private router: Router) {
  console.log(this.router.getCurrentNavigation().extras.state.hello); // should log out 'hello'
}

For better understanding read the documentation. PFB the link to documentation https://angular.io/api/router/NavigationExtras#state

Sign up to request clarification or add additional context in comments.

Comments

2

If you want to access inside ngOninit, use the location getState function which is available from angular 8+

import { Location } from '@angular/common';
 
export class AComponent
{
  
 
  constructor(private location:Location){
  }
 
  ngOnInit() {
    console.log(this.location.getState());
  }
}

Reference Link : https://www.tektutorialshub.com/angular/angular-pass-data-to-route/

Comments

0

For me, this.router.getCurrentNavigation() didn't work. Instead I used something like

history.state.hello

in the page navigated to and it worked

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.