Extract id from url using Angular2

Hi, I am trying to retrieve the url id using Angular2.

http://localhost:3000/item/187809 

I played with ActiveRoute inside onInit but with no luck

  this.route.queryParams.forEach((params: any) => { console.log("QUERYPARAMS"); console.log(params); }); 

Also tried to sign up for a route change as follows

 this.routeSub = this.route.queryParams.subscribe(params => { console.log(params); console.log(+params['id']); }); 

but params is just an empty object.

I define a route as a lazy route like this

 { path: item', children: [ { path: ':id', loadChildren: './item/item.module#ItemModule' }, ] }, 

I think the problem is that I have a header component and a main component that contains a lazy loaded routed child. I am trying to load an identifier inside a header component.

Any idea what is missing?

+21
source share
4 answers

Subscribe and unsubscribe to route options

1) Make sure you configure a route that expects such a parameter:

  {path: 'item/:id', component: SomeItemComponent} 

2) Declare a variable for your route subscription. Import ActivatedRoute (not ActiveRoute) and paste it into the component constructor.

  private routeSub: Subscription; constructor(private route: ActivatedRoute) { } 

3) Inside ngOnInit in the same component, you can access data in observable params by subscribing to them as follows:

  ngOnInit() { this.routeSub = this.route.params.subscribe(params => { console.log(params) //log the entire params object console.log(params['id']) //log the value of id }); } 

4) Unsubscribe inside ngOnDestroy to prevent memory leaks.

  ngOnDestroy() { this.routeSub.unsubscribe(); } 
+46
source

I know I was a bit late with the answer, but in case you still have a problem, please see the Angular documentation.

corner routing tutorial

Look at the example here.

Start by importing ActivatedRoute:

 import { ActivatedRoute } from '@angular/router'; 

Then enter it in the constructor

 constructor(private route: ActivatedRoute) {} 

And in OnInit ()

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

and like that you don’t need to worry about any Observables directly.

Hope this helps you.

+12
source

I suspect the problem is that you are using queryParams instead of params .

params: Observable, which contains the required and optional parameters specific to the route.

queryParams: Observable, containing query parameters available for all routes.

try the following:

 this.route.params.subscribe(params => { console.log(params); console.log(+params['id']); }); 
+5
source
 this.routeSub = this.route.params.subscribe(params => { console.log(params); console.log(+params['id']); }); 
+3
source

Source: https://habr.com/ru/post/1265560/


All Articles