angulartypescriptangular-routingquery-stringangular-activatedroute

Why ActivatedRoute.queryParams is not working in Angular?


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