getting query params from url Angular

603 Views Asked by At

I want to grab id from url

http://localhost:4200/courses/5a0eb3d7f6b50c2589c34e57
so in my app.module.ts I have such route
{path:'courses/:id', component:CourseComponent, canActivate:[AuthGuard]}
and in my course.component.ts I have the following code :

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-course',
  templateUrl: './course.component.html',
  styleUrls: ['./course.component.css']
})
export class CourseComponent implements OnInit {

  id: String;

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    this.id = this.route.snapshot.queryParams["id"];
    console.log(this.id)
  }

}

Actually in my developer console I can see following And if I try to console.log(params) I get following

2

There are 2 best solutions below

0
On BEST ANSWER

This is a route param and you should be using the params property

this.id = this.route.snapshot.params["id"];
0
On

You should use rxjs.

this.route.params.pluck('id').subscribe(v => console.log(v));

Preferable, since .params might be depracated soon:

this.route.paramMap.subscribe(paramMap => paramMap.get('id'));

Everything is in documentation... https://angular.io/guide/router#parammap-api