0

I have a routerlink that looks like this:

  <li class="list-group-item d-flex justify-content-between align-content-center" *ngFor = "let union of activeUnions" [routerLink] = "['union',union.id]">

Which is routing using the route:

const routes: Routes = [
  {
    path: '',
    component: IndexPage
  },
  {
    path:"new",
    component:NewPage
  },
  {
    path:"union/:id",
    component:UnionPage
  }
];

This is sending me to the required component but when i try to get the id like such


  ngOnInit() {
    let id = this.$common.$route.snapshot.paramMap
    console.log(id);
  }

I am getting an empty object instead of an object containing the id from the url, whats is wrong?

6
  • can anyone help? Commented Jan 15, 2022 at 17:23
  • You should probably try to provide a minimal reproducible example that clearly demonstrates the issue you are facing. Ideally, someone could drop the code into a standalone IDE like Stackblitz (link here!) and immediately get to work solving the problem without first needing to re-create it. There should be no typos, unrelated errors, or undeclared types or values. Commented Jan 15, 2022 at 17:51
  • Is the ID visible in the URL? Commented Jan 15, 2022 at 17:54
  • Yes the id is in the url @oscar Commented Jan 15, 2022 at 17:55
  • Move this code within constructor and see if that helps! Commented Jan 15, 2022 at 18:00

1 Answer 1

1

See if you can get the desired id with this:

...
import { ActivatedRoute } from '@angular/router';
...

constructor(
   ...
   private activatedRoute: ActivatedRoute
   ...
) {}


 ngOnInit(): void {
    const id = Number(this.activatedRoute.snapshot.paramMap.get('id'));
    console.log(id);
  }
Sign up to request clarification or add additional context in comments.

2 Comments

This must work, but remember that this captures the value of ID just once at the ngOnInit. If the id changes while the component is active, the value in the component won't change
This worked, this was what i was doing but the activatedRoute was in a common service that was imported together, why did this hinder it from working?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.