Search code examples
angularangular-routing

Angular 11,Route Parameters not working in my case


I have been facing the issue on angular parameters since path routing I am able to navigate but when it's coming to parameters calling I am unable to fetch the id

Issue: enter image description here

How to overcome this issue please help me on this

app-routing
----------
const routes: Routes = [
  {path:"", redirectTo:"home", pathMatch:"full"},
  {path:"home",component:HomeComponent},
  {path:"product",component:ProductComponent},`enter code here`
  {path:"prod-details/:id",component:ProductDetailsComponent},  
];

when I try to declare the variable it through the error

product-details.ts
--------------------
import { Component, OnInit } from '@angular/core';
    import { Router, ActivatedRoute} from '@angular/router';
    

@Component({
  selector: 'app-product-details',
  templateUrl: './product-details.component.html',
  styleUrls: ['./product-details.component.css']
})
export class ProductDetailsComponent implements OnInit {

  constructor(private rout:ActivatedRoute) { }
  product_id="";

  ngOnInit(): void {
   
  this.product_id = this.rout.snapshot.paramMap.get('id');
    
  }

}

Solution

  • This works

    ngOnInit() {
        this.activatedRoute.paramMap.subscribe(params => {
          if (params.get('id')) {
            this.paramId = params.get('id');
          }
        });
      }