angulartypescriptangular-routingangular-routerangular-routerlink

Forward state with navigateByUrl in Angular


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.


Solution

  • 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