Getting different results for params value in Angular 7

Viewed 56

I've been getting my hands on the new Angular version before this I had worked on below 2 versions. So, this is kind of new for me. I was working on a small project where I was working with routing and getting a value from params and passing it to a function to get results from an API. I got a strange outcome to this one.

I've two examples here:

First example

constructor(private router: ActivatedRoute, private movieService: MovieService) { }
this.router.params.subscribe((params) => {
  const id = params['id']; //this works fine
});

second example

constructor(private router: ActivatedRoute, private movieService: MovieService) { }
this.router.params.subscribe((params) => {
  const id = params.id;//this doesn't gives me undefined
});

If I'm not wrong aren't both methods for accessing object keys correct? I've not noticed such behaviour before. Am I missing something?

1 Answers

Firstly, do mention about your router variable. I think it is activatedRoute. Anyways, I have tried both ways of extracting the params and both works. Alternatively you could use ActivatedRouteSnapshot for extracting the params.

Here is the code using activated route snapshot

    const id = this.activatedRoute.snapshot.paramMap.get('id');

You can find more about activated route here

Related