Hi I am trying to extract the id part of the url using Angular2.
http://localhost:3000/item/187809
I have been playing around with ActiveRoute
You have multi options to get id
constructor(private route: ActivatedRoute) { }
1-With the help of params
const id= this.route.snapshot.params['id'];
or
const id = this.route.snapshot.params.id // any param name after "params"
2-With the help of paramMap
const id= this.route.snapshot.paramMap.get('id')
3-subscribe
to params
(do not forget to unsubscribe)
private subscription: Subscription
constructor(private route: ActivatedRoute) { }
ngOnInit(): void {
this.subscription = this.route.params.subscribe(params => {
const id = params['id']
})
}
//To prevent memory leak
ngOnDestroy(): void {
if (this.subscription)
this.subscription.unsubscribe()
}