Send data through routing paths in Angular

I needed access to the data in CustomRouteReuseStrategy and I couldn't inject the Router there due to a circular dependency but you can use the Location object to read the state as well.

Send:

    this.router.navigate(['action-selection'], { state: { example: 'bar' } });

Receive:
    import { Location } from '@angular/common';

    constructor(private location: Location) {
      console.log(this.location.getState().example); // should log out 'bar'
    }

There is a lot of confusion on this topic because there are so many different ways to do it.

Here are the appropriate types used in the following screen shots:

private route: ActivatedRoute
private router: Router

1) Required Routing Parameters:

enter image description here

2) Route Optional Parameters:

enter image description here

3) Route Query Parameters:

enter image description here

4) You can use a service to pass data from one component to another without using route parameters at all.

For an example see: https://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/

I have a plunker of this here: https://plnkr.co/edit/KT4JLmpcwGBM2xdZQeI9?p=preview


Latest version of angular (7.2 +) now has the option to pass additional information using NavigationExtras.

Home component

import {
  Router,
  NavigationExtras
} from '@angular/router';
const navigationExtras: NavigationExtras = {
  state: {
    transd: 'TRANS001',
    workQueue: false,
    services: 10,
    code: '003'
  }
};
this.router.navigate(['newComponent'], navigationExtras);

newComponent

test: string;
constructor(private router: Router) {
  const navigation = this.router.getCurrentNavigation();
  const state = navigation.extras.state as {
    transId: string,
    workQueue: boolean,
    services: number,
    code: string
  };
  this.test = "Transaction Key:" + state.transId + "<br /> Configured:" + state.workQueue + "<br /> Services:" + state.services + "<br /> Code: " + state.code;
}

Output

enter image description here

Hope this would help!


There is a new method what came with Angular 7.2.0

https://angular.io/api/router/NavigationExtras#state

Send:

    this.router.navigate(['action-selection'], { state: { example: 'bar' } });

Receive:

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

You can find some additional info here:

https://github.com/angular/angular/pull/27198

The link above contains this example which can be useful: https://stackblitz.com/edit/angular-bupuzn