4

I am using routing in my Angular app.

I have bellow route in my routing module.

{
    path: 'user/:name',
    component: UserComponent,
}

I am using queryParams of ActivatedRoute to get name from route. this is my code.

this.activatedRout.queryParams.subscribe( params => {

  this.user_name = params['name'];

});

But params are undefined. please help me.

Sudarshana Dayananda
  • 5,165
  • 2
  • 23
  • 45

5 Answers5

0

For understanding, you have a route look like user/karthik?style=awesome for example, the part karthik is the param :name , while you need style=awesome, which is the query param, that's why it is undefined.

If your intend is to subscribe for params changes, use paramMap, not queryParam.

this.activatedRout.paramMap.subscribe( params => {
 this.name = params['params']['name']
});

Or you can use params :

this.activatedRout.params.subscribe( params => {
 this.name = params['name'];
});
Mukul Kumar Jha
  • 1,062
  • 7
  • 19
Ethan Vu
  • 2,911
  • 9
  • 25
0

It should be params not queryParams

this.activatedRout.params.subscribe( params =>{this.user_name = params['name'];});

Chaitanya
  • 847
  • 1
  • 8
  • 15
0
this.activatedRout.params.subscribe(({name}) => {
    this.user_name = name;
});
lamnqd
  • 1
  • 2
0

I know there's an accepted answer here but it's missing a crucial detail about what queryParams is. Here are my notes:

// { path: 'user/:name'...

// access route params from router ie 'joe' from URL example.com/user/joe
this.route.params.subscribe(params => {
    console.log(params); // access the user name param 
});

// map your router parameter values
this.route.paramMap.subscribe(data => {
    console.log(data);
    // this.name = params['params']['name']
});

// access URL query parameters ie. example.com/?x=7680&y=4320
this.route.queryParams.subscribe(params => {
    console.log(params);
});
Ben Racicot
  • 5,332
  • 12
  • 66
  • 130
0

Access URL query parameters ie. http://localhost:4200/products?category=bread

route.queryParams.subscribe((params: any) => {
    this.category = params['category'];
    console.log(this.category);
});
Lightz
  • 11
  • 3