How to pass / receive data to components through routing

In my app-routing-module I will reuse the same component for four different routes, but I need to know a way to differentiate these components.

Currently my app-routing passes a title property in data:

  {
    path: 'x',
    loadChildren:'./pages/x/x-x/x-x.module#xModule',
    data: {
      title: 'x'
    }
  }

How do I retrieve this value in my component to do the logic I need?

Author: veroneseComS, 2019-07-12

4 answers

constructor(
    private route: ActivatedRoute,
    ) { }

ngOnInit(){
  let lastRoute=this.route;
  while(lastRoute.firstChild){
   lastRoute=firstChild
  }
  this.lastRoute.data.subscribe(data=>console.log(data)
 }
}
 1
Author: Eduardo Vargas, 2019-07-12 14:08:27

I solved as follows:

In my app-routing.modules :

{
    path: 'xxx',
    loadChildren:'./pages/xxx/xxx-xxx/xxx-xxx.module#xxxModule',
    data: {
      title: 'Título que vou passar'
    }
}

In my component :

public rotaAtual: Subscription;

constructor(
public route: ActivatedRoute){}

public getTitulo(): void {
    this.rotaAtual = this.route.data.subscribe((res) => {console.log(res)}
)}

public ngOnDestroy(): void {
    this.rotaAtual.unsubscribe();
}
 0
Author: veroneseComS, 2019-07-12 20:21:56

The way our friend Edward showed it is with parameters in the route, you can also pass query parameters which I believe to be the way you want to get.

By Your example it was not clear at what time you will change from one route to another, but I will give my example that would be a click on an anchor tag, it would look like this:

<a [routerLink]="['/rotaUtilizada']" [queryParams]="data:{title: 'Título que vou passar'}">
  Clique Aqui
</a>

This way through your this.router you manage to catch the passed parameter. Your URL will look like this: rotautilized?date= "title passed".

If you want to pass query parameter by ts just do as the exmeplo that our friend gave passing the queryParams property.

Nete article explains exactly what you are looking for: Angular Router

 0
Author: Enos Silva, 2019-07-23 16:34:23

Going through the date I haven't learned yet, I know how to do it this way:

{ path: 'artigo/edit/:id', component: RhFormArtigoComponent},
{ path: 'artigo/edit/:setor/:id', component: RhFormArtigoComponent},

In the component gets like this:

import { Router, ActivatedRoute } from "@angular/router";

constructor(
    private route: ActivatedRoute,
    ) { }

this.id_setor = this.route.snapshot.params.setor;
this.id = this.route.snapshot.params.id;
 -1
Author: Edward Ramos, 2019-07-15 12:40:10