How to pass/receive data to components via routing

Asked

Viewed 993 times

0

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 on the date:

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

How I recover that value in my component to make the logic I need?

4 answers

1

constructor(
    private route: ActivatedRoute,
    ) { }

ngOnInit(){
  let lastRoute=this.route;
  while(lastRoute.firstChild){
   lastRoute=firstChild
  }
  this.lastRoute.data.subscribe(data=>console.log(data)
 }
}
  • You’re taking the data through the URL?

  • Not by url, by route date property

  • And what about the code in the routing file? How it receives and sends the values?

  • is the same as the question for example. Values are statical.

  • I did something similar, I’ll add my answer

0

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

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

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

This way through your this.router you can get the parameter passed. Your URL will look like this: rotaused? data="".

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

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

0


I decided as follows:

In my app-routing.module:

{
    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();
}

-1

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 receives so:

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;
  • In case I wouldn’t like to leave this data on the link, I did it in a slightly different way but thanks anyway

  • What was the way you did it? @Veronesecoms

  • added an answer with the way I solved

Browser other questions tagged

You are not signed in. Login or sign up in order to post.