Get Query Parameters from an Angular Route
Dec 11, 2021
Angular provides access to the query parameters of the current route through the queryParams
property of ActivatedRoute
. queryParams
is an observable so we can subscribe to it to receive it's current value and any changes to it value.
The example below shows how a component can access the query parameters for a route such as:
http://localhost:4200/search?query=shoes&min_price=10&max_price=75
- The constructor requires an
ActivatedRoute
instance which Angular will provide (line 12). - In ngOnInit we subscribe to changes to
this.route.queryParams
and use the values for search for products (line 15–22).
Test a component that uses query parameters
Angular allows us to provide a configured instance of ActivatedRoute
with a set value for queryParams
.
- Configure the test to provide a set value of
queryParams
(line 17–22). - Construct a mock instance of
ProductService
(line 26–27). - Verify that out component used the values from
queryParams
to callproductService.search(...)
(line 39).