Question

Angular HTTP Query Parameters: Passing URL Arguments Safely

typescripthttpangular

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.

Take Quiz

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()
);

Angular produces a request equivalent to:

http://atsomeplace.com/?var1=val1&var2=val2

For current Angular applications, use HttpClient from @angular/common/http and HttpParams:

import { HttpClient, HttpParams } from '@angular/common/http';

const params = new HttpParams()
  .set('var1', 'val1')
  .set('var2', 'val2');

this.httpClient.get<Forecast>(StaticSettings.BASE_URL, { params }).subscribe({
  next: forecast => this.onGetForecastResult(forecast),
  error: error => this.onGetForecastError(error)
});

With HttpClient, parsed JSON is returned automatically, so there is no .json() call.

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 });
  1. new HttpParams() creates an empty parameter collection.
  2. .set('city', 'New York') returns a new collection containing city.
  3. .set('days', '5') returns another collection containing both parameters.
  4. HttpClient receives /api/forecast and the params collection.
  5. Before sending the request, Angular encodes the values. The space in New York is encoded for a URL.
  6. The server receives a URL equivalent to:
/api/forecast?city=New%20York&days=5
  1. If the server responds with JSON, HttpClient converts it into a JavaScript object before the next 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.

Take Quiz

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', city);

    if (days !== undefined) {
      params = params.set('days', String(days));
    }

    return this.http.get<Forecast>('/api/forecast', { params });
  }
}

Useful patterns include:

  • Optional filters: Only add a parameter when its value is present.
  • Validation: Reject invalid input before sending a request, such as a negative page number.
  • Typed responses: Use get<Forecast>() so TypeScript can check how the result is used.
  • Error handling: Handle HTTP errors with an RxJS catchError operator or an error callback.
  • Avoiding undefined: Do not serialize optional values accidentally as ?filter=undefined.

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:

let params = new HttpParams();
params = params.set('city', 'Paris');

Concatenating raw input into a URL

const url = '/api/search?q=' + searchText;

If searchText is tea & coffee, the & may be interpreted as another parameter. Use HttpParams so the value is encoded safely.

Mixing old and modern Angular APIs

  • @angular/http, URLSearchParams, { search: ... }, and response.json() belong together in legacy code.
  • @angular/common/http, HttpParams, { params: ... }, and automatic JSON parsing belong together in modern code.

Do not import HttpParams while still calling the old Http service.

Sending sensitive data in a query string

URLs can appear in browser history, server logs, proxy logs, and analytics tools. Do not place passwords, access tokens, or private personal data in query parameters. Use an appropriate secure request body or authorization header instead.

Comparisons

SituationLegacy Angular HttpModern Angular HttpClient
Import@angular/http@angular/common/http
Parameter typeURLSearchParamsHttpParams
Options propertysearchparams
JSON parsingCall response.json()Parsed automatically by default
StatusDeprecated/obsoleteRecommended
URL partExampleBest use
Route parameter/api/users/42Identifying one resource
Query parameter/api/users?role=adminFiltering, searching, paging, options
Request bodyPOST /api/users with JSONSending structured data to create or update something
Take Quiz

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 URLSearchParams();
search.set('page', '1');
this.http.get('/api/items', { search });
  • Use { params } with HttpClient.
  • HttpParams.set() returns a new instance.
  • Convert numbers and booleans to strings when building parameters.
  • Let Angular encode values; avoid manual URL concatenation.
  • Do not put secrets in query strings.

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?

No. HttpClient parses JSON responses by default.

Can I pass a JavaScript object directly as params?

Angular supports convenient object forms in many current HttpClient use cases, but HttpParams is explicit and especially useful for optional or repeated values. Use it when you need precise control.

Take Quiz

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.

Take Quiz

Keep learning

Related questions

View more