How does the angle router work?

-4

Good morning, I'm in doubt about router of angular2 to pass values to another page ... I do not know how to use it nor how it works, can they help? I have already seen several examples in forums, but I still do not understand what its function is, and how to use it ...

    
asked by anonymous 25.06.2018 / 13:36

1 answer

2

Bruno, There are several ways to use the router and pass parameter.

Via browser route:

In your routing.module:

import { NgModule, ModuleWithProviders} from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AgendaConfirmacaoComponent } from './agenda-confirmacao/agenda-confirmacao.component';


const agendaRoutes: Routes = [
  {
    path: 'agendaConfirm/:id',
    component: AgendaConfirmacaoComponent
  },
];

@NgModule({
  imports: [RouterModule.forChild(agendaRoutes)],
  exports: [RouterModule]
})
export class AgendaRoutingModule {}

In this code snippet you configure the routing, telling you what the route will be, and the: id indicates that you will receive a parameter. You are currently setting up a route that can be used.

In your html or component.ts you at some point call this route, I'll show you two ways:

<a routerLink="/agenda/agendaConfirm" [queryParams]="{id_agendamento: vlb.id}">Abrir</a>

See that I called the routerLink by calling the route, and in the queryParams I'm sending the named scheduling id to schedule_id.

In the component.ts of my calendar confirmation page I get this id like this:

 this.route.queryParams.subscribe(
        (queryParams: any) => {
          this.id_agendamento = queryParams['id_agendamento'];
        });

Note that the name used in the routerLink's queryParams is the same as the one I used to read this id in component.ts.

Another way to redirect to a page passing parameter is as follows:

this.router.navigate(['/agenda/agendaConfirm', this.idAgendamento]);

This line of code is another alternative to when it is in some method in component.ts and is redirected to the page by taking a parameter.

In the component.ts the reading will be as follows, if you choose to use navigate:

id_agendamento = this.route.snapshot.params['id']; 
//o id usado no 'params['id']' é o mesmo que foi nomeado no routing:

const agendaRoutes: Routes = [
      {
        path: 'agendaConfirm/:id',
        component: AgendaConfirmacaoComponent
      },
]; //Essa foi a rota que definimos lá em cima usando agendaConfirm/:id

I hope I have helped,

These are the forms I use most. Any doubt is just to say that I try to lighten a little more.

    
25.06.2018 / 14:25