Search code examples
angularroutesangular-routingngoninit

where is the best place to capture params of routes in Angular


I have this layout

layot

Each time I select a project in sidenav component I must show the relational data of that selected project in the maincontent component

The issue is that I have this in sidenav

link

that is, each selected project goes to a new route, so in the maincontent component I get the params of this route in ngOnInit

ngOnInit(): void {
let id=this.route.snapshot.paramMap.get('id');

But this code only executes once when I select another project this code does not execute.


Solution

  • The problem using snapshot is that this method only executes once in ngOnInit when the component is initialized.

    To watch any changes in param routes the option is using an Observable with parmMap

    ngOnInit(){
    this.route.paramMap.subscribe(
      params => {
        const id = params.get('id');
    
        console.log('MainContent:Proyecto Seleccionado: ', id);
    
        this.dataService.getDatosCabeceraProyecto(id)
        .subscribe(
          (data:Proyecto)=>this.proyecto=data,
          (err:any)=>console.log(err),
          ()=>console.log('MainContent: datos de proyecto recogidos')
        );
     }