2

What is the best way to take the value of my id in the current route (with ActivatedRoute or Router) ? And explain why :)

n°1

constructor(private route: ActivatedRoute) {}

ngOnInit() {
  this.id = this.route.snapshot.params['id']
}

n°2

constructor(private router: Router) {}

ngOnInit() {
 this.id = this.router.url.includes('id')
}
Tim
  • 162
  • 2
  • 10
  • Please define your parameters for "best" in objective terms. Opinion-based questions are off-topic on Stack Overflow. – TylerH Mar 10 '20 at 16:29

5 Answers5

4

It is better to subscribe to the paramMap

ngOnInit() {
  this.route.paramMap.subscribe(params => {
    this.id= params.get('id');
  });
}
talhature
  • 2,246
  • 1
  • 14
  • 28
  • Why it is better ? And you forgot to unsubscribe... – Tim Dec 23 '20 at 17:11
  • Good point @TimothyALCAIDE however it's left for brevity in my answer. And this is a better approach than manually iterating params or any other approach since you subscribe to the parameter map changes as it is supposed to be. – talhature Dec 30 '20 at 06:40
1

First declare in your constructor from ActivatedRoute from '@angular/router';

constructor ( private route: ActivatedRoute ){}

Then by using this code you will get your query params

this.route.queryParams.subscribe(params =>{ let Id = params ["Id"]; }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
1

You need to unsubscribe from anything you subscribe to to prevent memory leaks.


paramsSubscription$: Subscription;
id: string;

constructor(private route: ActivatedRoute, private router: Router) {}

ngOnInit() {
  this.paramsSubscription$ = this.route.paramMap.subscribe(
    (params: ParamMap) => {
      this.id = params.get("id");
  });
}

ngOnDestroy() {
  if (this.paramsSubscription$) this.paramsSubscription$.unsubscribe();
}
0
this.route.params.forEach((params: Params) => {
    const id = +params['id'];
    // more stuff
});
ankitkanojia
  • 3,072
  • 4
  • 22
  • 35
Seryoga
  • 793
  • 6
  • 15
-1

Import Router in component.

import { Router } from '@angular/router';

pass it in constructor

private router : Router

Now this will give router parameter

this.router.url;