Saad
Saad

Reputation: 1087

How to get parameters using "/:params" in Angular 2

I want to get parameters from a link similar to this "sample.com/product/45" using "product/:id", Here is my route declaration :

export const routes: Routes = [
  { path: 'product/:id', component: Product }
];

Here is the component class

export class Product implements OnInit, OnDestroy {
  id: number;
  private sub: any;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
       this.id = +params['id'];

       console.log(this.id); //I get undefined here
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }
}

when i tried to console.log() the id , i got undefined

Upvotes: 2

Views: 1031

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222722

Try this ,

ngOnInit() {
    this.id = this.activatedRoute.snapshot.params["id"];
}

Upvotes: 4

Related Questions