Question
How can I trigger an HTTP GET request from an Angular component and add URL query parameters to it?
I currently have this request:
this.http.get(StaticSettings.BASE_URL).subscribe(
(response) => this.onGetForecastResult(response.json()),
(error) => this.onGetForecastError(error.json()),
() => this.onGetForecastComplete()
);
StaticSettings.BASE_URL contains a URL without a query string, such as:
http://atsomeplace.com/
I need the request URL to include parameters such as:
http://atsomeplace.com/?var1=val1&var2=val2
How can I provide var1 and var2 as an object and let Angular serialize them into a correctly encoded query string?
Short Answer
Angular sends query parameters through the request options, rather than by manually concatenating strings. Older Angular applications using @angular/http use URLSearchParams; current Angular applications using HttpClient use HttpParams. Both APIs encode parameter values and build the query string for you.
Concept
A query string is the part of a URL after ?. It supplies optional named values to a server:
/products?category=books&page=2
In this example, category and page are query parameters. The server receives them separately from the URL path and can use them to filter, search, paginate, sort, or configure a response.
Do not build query strings by directly joining untrusted values into a URL. A value can contain spaces, &, ?, or other characters that have special meaning in URLs. Angular's parameter classes encode these values correctly.
The code in the question uses the deprecated @angular/http module, recognizable from response.json(). In that API, pass a URLSearchParams instance in the search option. In modern Angular, use HttpClient and pass an HttpParams instance in the params option.
Mental Model
Think of a URL as a delivery address and query parameters as labelled notes attached to the package.
- The path, such as
/forecast, says where the request goes. - Query parameters, such as
?city=Paris&units=metric, say what details the server should use.
A parameter builder such as HttpParams is an assistant that writes the notes in the correct URL format. You provide labels and values; it handles separators and escaping.
Syntax and Examples
For the legacy Angular Http service from @angular/http, create URLSearchParams and pass it as search:
import { Http, URLSearchParams } from '@angular/http';
const params = new URLSearchParams();
params.set('var1', 'val1');
params.set('var2', 'val2');
this.http.get(StaticSettings.BASE_URL, { search: params }).subscribe(
response => this.onGetForecastResult(response.json()),
error => this.onGetForecastError(error.json()),
() => this.onGetForecastComplete()
);
Step by Step Execution
Consider this modern Angular example:
const params = new HttpParams()
.set('city', 'New York')
.set('days', '5');
this.httpClient.get<Forecast>('/api/forecast', { params });
new HttpParams()creates an empty parameter collection..set('city', 'New York')returns a new collection containingcity..set('days', '5')returns another collection containing both parameters.HttpClientreceives/api/forecastand theparamscollection.- Before sending the request, Angular encodes the values. The space in
New Yorkis encoded for a URL. - The server receives a URL equivalent to:
/api/forecast?city=New%20York&days=5
- If the server responds with JSON,
HttpClientconverts it into a JavaScript object before the callback runs.
Real World Use Cases
Query parameters are common when a request needs optional input without changing the endpoint path:
- Search:
GET /api/products?q=headphones - Filtering:
GET /api/orders?status=paid - Pagination:
GET /api/articles?page=2&pageSize=20 - Sorting:
GET /api/users?sort=name&direction=asc - Date ranges:
GET /api/reports?from=2025-01-01&to=2025-01-31 - Map and weather data:
GET /api/forecast?latitude=48.86&longitude=2.35
Use query parameters for request options and filters. Use route parameters, such as /api/users/42, when the value identifies a specific resource.
Real Codebase Usage
In real projects, developers usually keep request construction inside a service rather than a component. The component asks for data; the service builds the endpoint and parameters.
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
interface Forecast {
temperature: number;
summary: string;
}
@Injectable({ providedIn: 'root' })
export class ForecastService {
constructor(private http: HttpClient) {}
getForecast(city: string, days?: number): Observable<Forecast> {
let params = new HttpParams().set(, city);
(days !== ) {
params = params.(, (days));
}
..<>(, { params });
}
}
Common Mistakes
Using a plain query object with Angular's HTTP options
This is not the option name used by either Angular HTTP API:
// Does not add query parameters.
this.httpClient.get('/api/forecast', {
query: { city: 'Paris' }
});
Use params with HttpClient, or search with the old Http service.
Ignoring HttpParams immutability
HttpParams is immutable. .set() does not modify the existing instance; it returns a new one.
let params = new HttpParams();
params.set('city', 'Paris'); // Incorrect: returned value is discarded.
Assign the returned value:
Comparisons
| Situation | Legacy Angular Http | Modern Angular HttpClient |
|---|---|---|
| Import | @angular/http | @angular/common/http |
| Parameter type | URLSearchParams | HttpParams |
| Options property | search | params |
| JSON parsing | Call response.json() | Parsed automatically by default |
| Status | Deprecated/obsolete | Recommended |
Cheat Sheet
// Modern Angular: @angular/common/http
import { HttpClient, HttpParams } from '@angular/common/http';
let params = new HttpParams();
params = params.set('page', '1');
params = params.set('pageSize', '20');
this.httpClient.get<Item[]>('/api/items', { params });
// Add repeated parameter values in modern Angular
const params = new HttpParams()
.append('tag', 'angular')
.append('tag', 'http');
// /api/items?tag=angular&tag=http
// Legacy Angular only: @angular/http
import { URLSearchParams } from '@angular/http';
const search = new ();
search.(, );
..(, { search });
FAQ
How do I pass query parameters in Angular HttpClient?
Create an HttpParams object and pass it in the { params } request option.
Why does HttpParams.set() not seem to work?
HttpParams is immutable. Store the value returned by .set(), or chain calls starting from new HttpParams().
Does Angular encode spaces and special characters in query parameters?
Yes. HttpParams serializes values into URL-safe query parameter values.
Can Angular send multiple values for the same query parameter?
Yes. Use .append() repeatedly, for example tag=angular&tag=http. Confirm that your server expects repeated keys.
Should I use URLSearchParams or HttpParams?
Use HttpParams in current Angular applications. URLSearchParams applies only to the old, deprecated @angular/http API.
Do I need response.json() with HttpClient?
Mini Project
Description
Build a small Angular API service that requests products using optional search, category, and pagination parameters. This mirrors a product-list page where the user can search and filter without manually building URLs.
Goal
Create a ProductService method that sends only the query parameters that have meaningful values.
Requirements
Define a Product interface with an id and name.
Create a service that injects Angular HttpClient.
Accept optional search text, category, page, and page size values.
Add only non-empty optional values to the query parameters.
Return a typed observable of products.
Keep learning
Related questions
@Directive vs @Component in Angular: Differences, Use Cases, and When to Use Each
Learn the difference between @Directive and @Component in Angular, including use cases, examples, and when to choose each.
Accessing Input Value from EventTarget in TypeScript
Learn why EventTarget has no value property in TypeScript and safely read values from HTML input events in Angular applications.
Angular (change) vs (ngModelChange): What’s the Difference?
Learn the difference between Angular (change) and (ngModelChange), when each fires, and which one to use in forms and inputs.