Sub topic 6
Query Parameters and Headers
This chapter assumes you already have a TodoService that injects HttpClient and makes typed GET requests, as built in the earlier chapters. You should also be comfortable with TypeScript optional properties and basic HTTP concepts such as query strings and request headers.
Most real APIs need more than a bare URL. A list endpoint might take page, limit and search values in the query string. Some endpoints expect headers such as Accept or a custom API version header. Angular provides two classes for these: HttpParams for query parameters and HttpHeaders for headers.
The working model: immutable builders
HttpParams and HttpHeaders are both immutable. Methods like set, append and delete never change the object you call them on. Each one returns a new instance that includes the change. This works well for chaining, but it also leads to the most common bug in this area.
let params = new HttpParams();
params.set('page', 2); // Bug: the result is thrown away
params = params.set('page', 2); // Correct: keep the new instanceThe methods you will use most often:
| Method | Effect |
|---|---|
| `set(name, value)` | Replaces all values for `name` |
| `append(name, value)` | Adds another value, so `name` can repeat |
| `delete(name)` | Removes `name` |
| `has(name)` / `get(name)` | Reads the current state |
Building parameters conditionally
Filters are often optional. You don't want ?search=undefined in your URL, so add each parameter only when it has a value:
// todo.service.ts (additions)
import { HttpHeaders, HttpParams } from '@angular/common/http';
export interface TodoFilters {
page: number;
search?: string;
completed?: boolean;
tags?: string[];
}
// Inside TodoService
searchTodos(filters: TodoFilters): Observable<Todo[]> {
let params = new HttpParams().set('page', filters.page);
if (filters.search) {
params = params.set('search', filters.search);
}
if (filters.completed !== undefined) {
params = params.set('completed', filters.completed);
}
for (const tag of filters.tags ?? []) {
params = params.append('tag', tag);
}
const headers = new HttpHeaders({
Accept: 'application/json',
'X-Api-Version': '2'
});
return this.http.get<Todo[]>(this.baseUrl, { params, headers });
}If you call searchTodos({ page: 1, completed: false, tags: ['home', 'urgent'] }), Angular sends a request to /api/todos?page=1&completed=false&tag=home&tag=urgent. Because append was used for the tags, the tag key appears twice. With set, only urgent would remain.
The completed check compares against undefined because false is a valid filter value. A plain if (filters.completed) would silently drop it.
Shortcuts with plain objects
For simple cases you can skip the classes. Both options accept object literals:
this.http.get<Todo[]>(this.baseUrl, {
params: { page: 1, tag: ['home', 'urgent'] },
headers: { 'X-Api-Version': '2' }
});An array value becomes a repeated key. HttpParams also has a fromObject option: new HttpParams({ fromObject: { page: 1 } }). That gives you an instance you can keep building on.
Common errors
- Calling
setorappendwithout reassigning the result, so the request goes out with no parameters. - Using
setin a loop when you needappend, so only the last value is kept. - Adding the same header, such as an auth token, by hand in every service method. Headers that every request needs belong in an interceptor, which a later chapter covers.
- Expecting
headers.get('X-Total-Count')to work on a normal response. Response headers are only available when you request the full response withobserve: 'response'.
Exercise
A developer writes const params = new HttpParams(); ['a', 'b'].forEach(t => params.append('tag', t)); this.http.get(url, { params });. What query string is sent, and how do you fix it?
Show answer
No query string is sent, because append returns a new HttpParams and each result is discarded. Declare params with let and reassign it, as in params = params.append('tag', t), or pass { params: { tag: ['a', 'b'] } }. Either fix produces ?tag=a&tag=b.
Exercise
Why does the searchTodos method check filters.completed !== undefined instead of if (filters.completed)?
Show answer
The value false is a meaningful filter that asks for incomplete todos. A truthiness check would skip it and leave the completed parameter out entirely.