Search code examples
angularangular-router

Route action does not work on a component and different parameters


Route action does not work on a component and different parameters.

I have a component that gets different parameters, as follows below. However, when entering the component routes, it loads only once and the...

this.route.snapshot.params['id'] Not updated.

Routes

export const ROUTES: Routes = [
    {path: '', component: AppComponent,
        children: [
            { path: '', redirectTo: 'home', pathMatch: 'full'},
            { path: 'home', component: HomeComponent },
            { path: 'categoria/:id', component: ListaComponent },
            { path: 'player/:id', component: PlayerComponent }]
    }]

Component

import {Component, OnInit } from '@angular/core';
import { PostServices } from '../postServices';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'net-lista',
  templateUrl: './lista.component.html',
})
export class ListaComponent implements OnInit {

    order: any;

  constructor(private postServices: PostServices, private route: ActivatedRoute) {

  }

  ngOnInit() {
      this.postServices.getPostByCategory(this.route.snapshot.params['id']).subscribe( (res) => {
          this.order = res;
      })
  }

}

Solution

  • Snapshot value will give you just the first value of the parameter , instead subscribe to the this.route.params Observable and every time the parameter id in the route change the Observable will resolve:

     ngOnInit() {
              this.route.params.subscribe((params)=>{
              this.postServices.getPostByCategory(params["id"]).subscribe( (res) => {
                  this.order = res;
               })
           })
      }