Headers and params help you send extra information with your web requests. This lets servers know what you want or how to handle your request.
0
0
Setting headers and params in Angular
Introduction
When you need to send an API key or token to access protected data.
When you want to filter or sort data by sending query parameters.
When you want to tell the server the type of data you accept or send.
When you want to customize requests with language or format preferences.
When you want to send pagination info like page number or size.
Syntax
Angular
const headers = new HttpHeaders({ 'Header-Name': 'value' }); const params = new HttpParams().set('paramName', 'paramValue'); this.http.get(url, { headers, params });
Use
HttpHeaders to set request headers as key-value pairs.Use
HttpParams to add query parameters to the URL.Examples
Sends a GET request with an Authorization header carrying a token.
Angular
const headers = new HttpHeaders({ 'Authorization': 'Bearer token123' }); this.http.get('/api/data', { headers });
Sends a GET request with query parameters page=2 and limit=10 to control pagination.
Angular
const params = new HttpParams().set('page', '2').set('limit', '10'); this.http.get('/api/items', { params });
Sends a POST request with JSON content type header and a search query parameter.
Angular
const headers = new HttpHeaders().set('Content-Type', 'application/json'); const params = new HttpParams().set('search', 'book'); this.http.post('/api/search', { data: 'example' }, { headers, params });
Sample Program
This Angular component has a button. When clicked, it sends a GET request with an Authorization header and two query parameters. The response is shown below the button in JSON format.
Angular
import { Component } from '@angular/core'; import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; @Component({ selector: 'app-root', template: `<button (click)="fetchData()">Fetch Data</button><pre>{{response | json}}</pre>` }) export class AppComponent { response: any; constructor(private http: HttpClient) {} fetchData() { const headers = new HttpHeaders().set('Authorization', 'Bearer mytoken123'); const params = new HttpParams().set('category', 'books').set('limit', '5'); this.http.get('https://api.example.com/items', { headers, params }) .subscribe(data => this.response = data); } }
OutputSuccess
Important Notes
Headers and params are immutable. Use set or append methods to create new instances.
Always encode params properly; Angular's HttpParams handles this automatically.
Use headers to send tokens or content types; use params for filtering or pagination.
Summary
Headers add extra info to requests, like tokens or content types.
Params add query data to URLs, like filters or page numbers.
Use Angular's HttpHeaders and HttpParams classes to set them cleanly.