Home > front end >  NgOnInit executing only once
NgOnInit executing only once

Time:03-10

I've done this many times in my projects but I don't know why this is happening. I have a simple list

<mat-list>
        <mat-list-item *ngFor="let indicador of indicadores" [routerLink]="['/indicador', indicador.codigo]">
            <div mat-line>
                <div >
                    {{(indicador.nombre}}                        
                </div>
            </div>                
        </mat-list-item>

    </mat-list>

this is my 'indicador' code:

export class IndicadorComponent implements OnInit {

  id: string;
  indicador;

  constructor(private route: ActivatedRoute, private is: IndicadoresService) { 
  }

  ngOnInit(): void {
    this.id = this.route.snapshot.paramMap.get("id")
    this.is.obtenerIndicador(this.id).subscribe(data => {
      this.indicador = data;
      console.log(this.indicador)
    })

 }

The call to the service works fine the first time I click on an item, but when I click again in another item of the list, it only changes de url but does not execute the ngoninit method. In my app.componen.html I have the router-outlet properly and added the route of 'indicador' to the app-routing.module.ts

CodePudding user response:

That's because the router reuses components when only parameters change.

To fix this, subscribe to the observable parameters rather than just reading their snapshot:

this.route.paramMap.pipe(
    switchMap(paramMap => this.is.obtenerIndicador(paramMap.get("id")))
).subscribe(data => {
    this.indicador = data;
});
  • Related