0

I am getting data in abc.component.ts and trying to pass this data to component which is routed.`

This data should not be pass alongwith routes, since it is a json object and it can be very big data and route url will expose data.

.ts

data = {"key":1,"value":2}

this.router.navigate(['dashboard']); //<=== when routing pass 'data' into dashboard.component.ts

this.router.navigate(['page']); //<=== when routing pass 'data' into page.component.ts

.html

<router-outlet></router-outlet>

dashboard.component.ts

alert(data) <============ requirement
Mahi
  • 3,748
  • 4
  • 35
  • 70

3 Answers3

0

In your routing component, simply add another object called data, populate it with whatever you might need, for example:

{
    path: "path:/id",
    component: MyComponent,
    data: {
        type: "static"
    }
},

Then, simply subscribe for the data in the respective component, for example:

NOTE: You need to add ActivatedRoute (as shown) in your constructor for this to work.

constructor(private route: ActivatedRoute) {}

ngOnInit() {
    this.route.data.subscribe(data => {
        const type = data.type;
    }
}

EDIT: Here is another valuable resource.

EDIT 2: Another valuable resource here, which states that you can pass the data as a second parameter using the .navigate() method, e.g. - this.router.navigate(['/heroes', { id: heroId, foo: 'foo' }]);

Tanasos
  • 3,928
  • 4
  • 33
  • 63
0

You can pass it as a second parameter to navigate function.

data = {"key":1,"value":2}
this.router.navigate(['dashboard'], data);
Thyagarajan C
  • 7,915
  • 1
  • 21
  • 25
0
const routes = [
     {
        // ...
        component: AppComponent,
        children: [
             {
                 // ...
                 component: ChildRouteComponent
             }
        ]
     }
];

You inject the AppComponent into the child component.

@Component({...})
export class ChildRouteComponent {

    public constructor(app: AppComponent) {
        console.log(app.getData());
    }
}

The AppComponent has to provide the function getData() or a public property. Anything you want from the parent component to the child.

If the data is async, then have getData() return an observable of the data.

Reactgular
  • 52,335
  • 19
  • 158
  • 208