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.
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:
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
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.
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!