Pass data in Angular router dynamically

I am trying to send data(Object) from one component to another however I am getting an empty result.

Here is my code

routing module

{ path: 'booking/details', component: DetailsComponent, data: { title: extract('Details'), dataTransfer: '' } },

sending component

this.router.navigate(['/booking/details', this.caseData]);

this.caseData looks like this

{
  "getAllInfo": {
    "ticket": {
      "internalNum": "12345",
      "comp": "11"
    },
    "caseInfo": {
      "masVolgnommer": "1",
      "masMaand": "1",
      "masJaar": "2010"
    }
  }
}

receiving component

this.caseData = this.route
 .data
 .subscribe(v => console.log(v.dataTransfer));

2 answers

  • answered 2018-11-08 06:18 Sachila Ranawaka

    set the caseData inside the subscribe method

    this.route
     .data
     .subscribe(v => {
       this.caseData = v;
       console.log(this.caseData) 
    });
    

  • answered 2018-11-08 06:44 Rahul

    Data property is not needed in your route - without adding data you can bind data as a json and read it { path: 'booking/details', component: DetailsComponent } this is fine to pass data while routing - whereas data property in your route declaration is used to pass data every time when the route is navigated

    When you try to navigate booking/details everytime you will get data {title: "Details", dataTransfer: ""} to read this data you can inject ActivatedRouteSnapshotin your constructor and read as

    this.activatedRouteSnapshot.data["title"]this will return Details

    In your case if you want to pass data to another component just pass the data as a Json

    this.router.navigate(['/booking/details', { caseData : this.caseData }]);

    Finally you can read the data in the same way mentioned above - this.activatedRouteSnapshot.data["caseData"]

    Hope this works - Happy coding !!