Search code examples
angularangular-routing

How to use params property of ActivatedRouteSnapshot to populate data differently in a component


Imagine a situation where we have a single component which has to be populated with data differently based on different url parameters coming in.

That is, consider the below url patterns:

1. http://localhost:4200/venues/5760665662783488 
2. http://localhost:4200/users/2gjmXELwGYN6khZgzaeWKmLtIDt2 
3. http://localhost:4200/revenue 

Within the component, If i use ActivatedRouteSnapshot interface to log the parameters of my incoming urls, i get below results:

1. {venueid: "5760665662783488"}
2. {userid: "2gjmXELwGYN6khZgzaeWKmLtIDt2"}
3. {}

Now, if i want to populate fields of my single component in three different ways based on the three different url parameters like above, how can do so?

I mean how can i populate differently for incoming venueid/userid/{}? Is there a method on the ActivatedRouteSnapshot interface to check the key of the params object?

I tried looking through the documentation for ActivatedRouteSnapshot interface but did not find an answer.

Snip of my code to log the url params: console.log(this.activatedRoute.snapshot.params);

I would like to learn different ways to achieve this functionality if there exist few. Thanks in advance.


Solution

  • Well the ActivatedRouteSnapshot has a paramMap property and the ParamMap class has the .has(paramName) method for this.

      if(myActivatedRouteSnapshot.paramMap.has('userid')) {
        ...
      }
    

    Where myActivatedRouteSnapshot is the ActivatedRouteSnapshot you speak of.

    https://angular.io/api/router/ActivatedRouteSnapshot#paramMap https://angular.io/api/router/ParamMap