How do you get query parameters?
Query parameters (for example, ?page=2&sort=asc) are obtained through the ActivatedRoute service.
There are two approaches - a one-time read and subscribing to changes:
1. One-time read (snapshot)
typescript
constructor(private route: ActivatedRoute) {}
ngOnInit() {
const page = this.route.snapshot.queryParamMap.get('page');
const sort = this.route.snapshot.queryParamMap.get('sort');
}This is simple - it takes the values at the moment the component is entered.
2. Subscription (reacting to changes)
typescript
this.route.queryParams.subscribe(params => {
const page = params['page'];
const sort = params['sort'];
});Needed if the parameters can change while the component is active (for example, when filtering without a reload).
Where do query parameters come from? From a URL like:
javascript
/products?page=2&sort=ascAngular does not reload the component, but it does track the parameters.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.