Sub topic 6
Query Parameters and Headers
Most real API calls carry more than a URL. A list endpoint needs a page number, a search term and maybe a sort order. Other endpoints need an API version header or a request ID. Angular gives you two classes for this, HttpParams and HttpHeaders. Both are immutable, and that one design choice causes most of the mistakes people make with them.
This chapter assumes you can already write a typed GET request in a data service that injects HttpClient (covered in the earlier chapters). It also assumes you know what a query string and an HTTP header are.
The Two Ways to Pass Parameters
The params option on every HttpClient method accepts either an HttpParams instance or a plain object. Both produce the same request:
import { HttpClient, HttpParams } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { Observable } from 'rxjs';
export interface Todo {
id: number;
title: string;
completed: boolean;
}
@Injectable({ providedIn: 'root' })
export class TodoService {
private readonly http = inject(HttpClient);
private readonly baseUrl = '/api/todos';
// Option 1: an HttpParams instance
getTodos(page: number): Observable<Todo[]> {
const params = new HttpParams().set('page', page);
return this.http.get<Todo[]>(this.baseUrl, { params });
}
// Option 2: a plain object
getTodosPlain(page: number): Observable<Todo[]> {
return this.http.get<Todo[]>(this.baseUrl, { params: { page } });
}
}Both send GET /api/todos?page=1. The plain object is shorter and fine when the parameter set is fixed. HttpParams is better when you build parameters step by step, add repeated keys, or need a custom encoder.
The plain object form accepts values of type string | number | boolean or a read-only array of those. Arrays become repeated keys: { tag: ['work', 'urgent'] } produces ?tag=work&tag=urgent.
HttpParams Is Immutable
Every method that changes an HttpParams instance returns a new instance and leaves the original untouched. This is the most common bug in this area:
import { HttpParams } from '@angular/common/http';
// Wrong: the result of set() is thrown away
const broken = new HttpParams();
broken.set('page', 1);
broken.set('sort', 'title');
console.log(broken.toString()); // ""
// Right: keep the returned instance
let params = new HttpParams();
params = params.set('page', 1);
params = params.set('sort', 'title');
console.log(params.toString()); // "page=1&sort=title"
// Also right: chain the calls
const chained = new HttpParams().set('page', 1).set('sort', 'title');
console.log(chained.toString()); // "page=1&sort=title"The broken version compiles and runs without warnings. The request simply goes out with no query string, and you only notice when the server returns page 1 every time.
Immutability is deliberate. Interceptors (a later chapter) can see and change requests on their way out. If parameter and header objects were mutable, one piece of code could change a request another piece already holds a reference to. With immutable objects, sharing is safe.
The HttpParams API
| Method | What it does | Returns | Column |
|---|---|---|---|
| `set(name, value)` | Replaces all values for `name` with one value | New `HttpParams` | |
| `append(name, value)` | Adds a value, keeping existing ones | New `HttpParams` | |
| `appendAll(object)` | Appends several keys at once | New `HttpParams` | |
| `delete(name, value?)` | Removes all values for `name`, or only the given value | New `HttpParams` | |
| `has(name)` | Checks whether `name` is present | `boolean` | |
| `get(name)` | First value for `name`, or `null` | `string \ | null` |
| `getAll(name)` | All values for `name`, or `null` | `string[] \ | null` |
| `keys()` | All parameter names | `string[]` | |
| `toString()` | The encoded query string | `string` |
You can also build an instance from existing data with the constructor options fromObject and fromString:
import { HttpParams } from '@angular/common/http';
const a = new HttpParams({ fromObject: { page: 2, tag: ['work', 'home'] } });
console.log(a.toString()); // "page=2&tag=work&tag=home"
const b = new HttpParams({ fromString: 'page=3&sort=title' });
console.log(b.get('sort')); // "title"fromString is handy when you are forwarding a query string you received from somewhere else, such as the current router URL.
Building Parameters Conditionally
Search screens often have optional filters. You want each filter in the query string only when the user set it. Sending ?status=undefined or ?q= breaks many backends.
Angular converts each value to a string. An undefined or null that reaches set() or a fromObject map can end up in the URL as the literal text undefined or null. Filter these values out yourself:
import { HttpClient, HttpParams } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { Observable } from 'rxjs';
export interface Todo {
id: number;
title: string;
completed: boolean;
}
export interface TodoFilter {
page: number;
pageSize?: number;
search?: string;
completed?: boolean;
tags?: string[];
}
@Injectable({ providedIn: 'root' })
export class TodoSearchService {
private readonly http = inject(HttpClient);
search(filter: TodoFilter): Observable<Todo[]> {
let params = new HttpParams().set('page', filter.page);
if (filter.pageSize !== undefined) {
params = params.set('pageSize', filter.pageSize);
}
if (filter.search && filter.search.trim() !== '') {
params = params.set('q', filter.search.trim());
}
if (filter.completed !== undefined) {
params = params.set('completed', filter.completed);
}
for (const tag of filter.tags ?? []) {
params = params.append('tag', tag);
}
return this.http.get<Todo[]>('/api/todos', { params });
}
}Calling search({ page: 1, completed: false, tags: ['work'] }) sends GET /api/todos?page=1&completed=false&tag=work. Note the check filter.completed !== undefined. A truthiness check like if (filter.completed) would drop false, which is a meaningful filter value.
Parameters Already in the URL
If the URL string already has a query string, Angular joins your params to it with &. So http.get('/api/todos?archived=true', { params: { page: 1 } }) requests /api/todos?archived=true&page=1. This works, but splitting one query between two places makes it hard to read. Pick one place, preferably params, so encoding stays consistent.
Encoding
HttpParams encodes keys and values through an HttpParameterCodec. The default, HttpUrlEncodingCodec, starts from encodeURIComponent and then puts back a few characters, such as :, ,, ;, =, / and @, that are legal in a query string. Most servers accept that. Some strict backends, or signed URLs where the signature covers the exact query string, need every reserved character percent-encoded. For those cases, supply your own codec:
import { HttpParameterCodec, HttpParams } from '@angular/common/http';
export class StrictEncoder implements HttpParameterCodec {
encodeKey(key: string): string {
return encodeURIComponent(key);
}
encodeValue(value: string): string {
return encodeURIComponent(value);
}
decodeKey(key: string): string {
return decodeURIComponent(key);
}
decodeValue(value: string): string {
return decodeURIComponent(value);
}
}
const params = new HttpParams({ encoder: new StrictEncoder() })
.set('range', '2026-01-01,2026-12-31')
.set('q', 'a+b');
console.log(params.toString());
// "range=2026-01-01%2C2026-12-31&q=a%2Bb"Don't encode values yourself before passing them to set(). If you do, the codec encodes them a second time, and %20 turns into %2520.
HttpHeaders
HttpHeaders follows the same rules: it is immutable, and set, append and delete return new instances. Header names are case-insensitive, so get('content-type') finds a header you set as Content-Type.
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { Observable } from 'rxjs';
export interface Todo {
id: number;
title: string;
completed: boolean;
}
@Injectable({ providedIn: 'root' })
export class VersionedTodoService {
private readonly http = inject(HttpClient);
getTodo(id: number): Observable<Todo> {
const headers = new HttpHeaders()
.set('Accept', 'application/json')
.set('X-Api-Version', '2')
.set('X-Request-Id', crypto.randomUUID());
return this.http.get<Todo>(`/api/todos/${id}`, { headers });
}
// The plain-object form works too
getTodoPlain(id: number): Observable<Todo> {
return this.http.get<Todo>(`/api/todos/${id}`, {
headers: { 'X-Api-Version': '2' }
});
}
}The constructor also accepts an object (new HttpHeaders({ 'X-Api-Version': '2' })). Values can be a string or an array of strings when a header repeats.
Headers You Usually Should Not Set
| Header | Why to leave it alone |
|---|---|
| `Content-Type` for JSON bodies | `HttpClient` sets `application/json` when the body is a plain object. |
| `Content-Type` for `FormData` | The browser must set it so it can add the multipart boundary. Setting it yourself breaks the upload. |
| `Host`, `Content-Length`, `Cookie` | Browsers forbid scripts from setting these and silently ignore them. |
| `Authorization` on every call | Repeating it in each service method leads to drift. An interceptor (later chapter) does this in one place. |
Custom Headers and CORS
When your API runs on a different origin, any custom request header such as X-Api-Version makes the browser send a preflight OPTIONS request first. The server must list the header in Access-Control-Allow-Headers, or the real request never leaves the browser. Angular reports this as an HttpErrorResponse with status 0, which looks the same as a network outage. Check the browser's network tab for a failed OPTIONS call.
Response headers have a similar rule. JavaScript can read only a short list of "safe" response headers unless the server names the others in Access-Control-Expose-Headers. If X-Total-Count is always null on a cross-origin call, the server is not exposing it. Reading response headers at all requires observe: 'response', covered in a later chapter.
Common Errors at a Glance
| Symptom | Likely cause |
|---|---|
| Query string is empty | Result of `set()` or `append()` was not reassigned |
| `?status=undefined` in the URL | An optional value was passed without filtering |
| Duplicate keys like `page=1&page=2` | `append()` used where `set()` was meant |
| `%2520` in the URL | Value encoded manually before `set()` |
| Custom header missing on the server, `status` 0 in the browser | CORS preflight rejected the header |
| Response header reads `null` | Header not listed in `Access-Control-Expose-Headers`, or `observe: 'response'` not used |
Exercise
A teammate writes the code below, and the server always receives the request with no query string. Explain why and rewrite the method so it sends page and an optional sort parameter. getTodos(page: number, sort?: string) { const params = new HttpParams(); params.set('page', page); if (sort) { params.set('sort', sort); } return this.http.get<Todo[]>('/api/todos', { params }); }
Show answer
HttpParams is immutable. Each set() call returns a new instance, and this code throws those instances away, so the original empty params goes out with the request. Fix it by reassigning the result: getTodos(page: number, sort?: string) { let params = new HttpParams().set('page', page); if (sort) { params = params.set('sort', sort); } return this.http.get<Todo[]>('/api/todos', { params }); }
Exercise
You need to request /api/todos?tag=work&tag=urgent&completed=false. Write it once with a plain object and once with HttpParams.
Show answer
Plain object: this.http.get<Todo[]>('/api/todos', { params: { tag: ['work', 'urgent'], completed: false } }). HttpParams: new HttpParams().append('tag', 'work').append('tag', 'urgent').set('completed', false). The second tag needs append(), because set() would replace the first value.
Exercise
Your cross-origin API call adds the header X-Api-Version. In development, where the API shares an origin with the app, it works. In staging, every call fails with status 0 and an OPTIONS request appears in the network tab. What is happening, and who needs to fix it?
Show answer
The custom header turns the cross-origin call into one that needs a CORS preflight. The staging server's OPTIONS response does not list X-Api-Version in Access-Control-Allow-Headers, so the browser blocks the real request and Angular reports status 0. The fix belongs on the server: allow the header in its CORS configuration. Nothing in the Angular code needs to change.