Retrieve Parameters and Query String values from URL in Angular 8

    Sep 27, 2019       by Pankaj Kumar
angular8-url-params.jpg

While working with angular, Many times we need to get data from URL. Data in url can be passed in two ways, first as a parameter and second as a query string. Sometimes we get confuse while fetching data from the url. Let's have a look.

 

1. Accessing Query String Values From URL

We can get the value of query parameters using ActivatedRoute object, queryParamMap. Let's have an example below:

Dummy URL : http://localhost:4200/user-list?type=normal&list=active

For accessing the value from above url we can have code like below:

 

 
ngOnInit() {
    // first way
    this.userType = this.route.snapshot.queryParamMap.get("userType");
    this.list = this.route.snapshot.queryParamMap.get("list");
    // second way
    this.route.queryParamMap.subscribe(queryParams => {
       this.userType = queryParams.get("userType");
       this.list = queryParams.get("list");
    })
}
 

 

2. Accessing the URL Parameters

Angular comes us with the ActivatedRoute object. We can access the URL parameter value in same way its done above with little difference. Data in this type can be accessed with two different ways. One is through route.snapshot.paramMap and the other is through route.paramMap.subscribe. The main difference between the two is that the subscription will continue to update as the parameter changes for that specific route. 

Dummy URL : http://localhost:4200/user-list/normal/active

Snapshot

ngOnInit() {
  this.userType = this.route.snapshot.paramMap.get("userType")
}

 

Subscription

 

 
ngOnInit() {
    this.route.paramMap.subscribe(params => {
        this.userType = params.get("userType")
    })
}
 

 

Note: Using subscribe is best way to get the value from URL because if value changes within same route then value get updated in the variable. When we use snapshot then value does not update if value of userType updates in same route.

 

Conclusion

Retrieving values from URL is not a big task with in Angular application, But basic understanding of receiving values in different ways is neccessary for a developer.

Click here to see Angular Sample Projects to get started for enterprise-level application.

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.

Thank You!


WHAT'S NEW

Find other similar Articles here: