route.queryParams.subscribe returns undefined in Angular Typescript Component

Viewed 2560

I need to pass id as parameter to my angular component

In my html i have something like this

<a [routerLink]="['/viewjobdetail',  currentJob.id]">
    {{ currentJob.title }}
</a>

app.module.ts RouterModule.forRoot configured as

  { path: 'viewjobdetail/:id', component: JobDetailComponent }

in my calling component i have

import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute){}

ngOnInit(): void {
this.route.queryParams.subscribe(params => {
  debugger;
  var a = params['id'];
  this.displayJobId = parseInt(params['id']);
});

But when i check it its always showing undefined for a, what i am doing wrong here? }

2 Answers

You should use params or paramMap instead of queryParams, query params can only recognise query params passed like viewjobdetail?id=23

queryParams is better since params may be deprecated in future releases

this.route.paramMap.subscribe(paramMap => {
  debugger;
  var a = paramMap.get('id');
  this.displayJobId = parseInt(a);
});

I got the solution. to achieve thiswe need to use query parameters with queryParams. I modified my html as below

<a [routerLink]="['/viewjobdetail']" [queryParams]="{id: currentJob.id}">
{{ currentJob.title }}
</a>

and in app.module.ts

{ path: 'viewjobdetail', component: JobDetailComponent }

and then in my calling component

  this.route.queryParams.subscribe(params => {
  
  var a = params.id;
  }
Related