0

I want to pass data using routing by passing data directly in the routing, see example to be more clear. I try to do it this way to see all the possibilities to pass from the given.

In my example I want to pass the variable toto to another component

Thanks in advance.

one component

public toto:string = 'pass this data to two component'

routing.module

const routes: Routes = {
 { 
   path: 'two',
   component: TwoComponent,
    data: toto // I have an error here that says cannot find 'toto
 }
}
Herge
  • 47
  • 1
  • 8
  • 1
    Does this answer your question? [How do I pass data to Angular routed components?](https://stackoverflow.com/questions/36835123/how-do-i-pass-data-to-angular-routed-components) – Yong Shun Aug 23 '21 at 07:47

1 Answers1

0

You dont need to put data in {} as data is a property of Routes type, instead do this:

{
   path: 'two',
   component: TwoComponent,
   data:  { //pass your data as object}
}

or even:

   {
       path: 'two',
       component: TwoComponent,
       data:  _variable //if you don't need to use object
    }
Qiimiia
  • 510
  • 6
  • 16
  • thank you for your help, can I pass my variable toto in to retrieve it in another component? – Herge Aug 23 '21 at 07:45
  • Sure. In `ngOnInit` in `TwoComponent` use this code: `this.activatedroute.data.subscribe(data => {//access data})` – Qiimiia Aug 23 '21 at 07:50
  • Also don't forget to `import { ActivatedRoute } from '@angular/router'` – Qiimiia Aug 23 '21 at 07:51
  • when I try I get this error : ' Cannot find ' toto' why ? the error comes from my routing – Herge Aug 23 '21 at 08:17
  • `toto` is a local variable in `OneComponent` and it can't be access in `routing.module`. You don't need to path data in your module. Do it in your `TwoComponent` itself. Here is a link t guide you: https://www.tektutorialshub.com/angular/angular-pass-data-to-route/ – Qiimiia Aug 23 '21 at 08:27