JavierOrellana7
JavierOrellana7

Reputation: 59

NgOnInit executing only once

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 class="divisa">
                    {{(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

Upvotes: 0

Views: 1086

Answers (1)

meriton
meriton

Reputation: 70564

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

Upvotes: 1

Related Questions