Why ActivatedRoute.queryParams is not working in Angular?

0

Issue

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.

Solution

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'];
});

Answered By – Ethan Vu

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More