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.
Setting headers and params in Angular
Introduction
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
Angular
const headers = new HttpHeaders({ 'Authorization': 'Bearer token123' }); this.http.get('/api/data', { headers });
Angular
const params = new HttpParams().set('page', '2').set('limit', '10'); this.http.get('/api/items', { params });
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); } }
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.
Practice
1. What is the main purpose of setting headers in an Angular HTTP request?
easy
Solution
Step 1: Understand what headers do
Headers carry extra info like tokens or content type in HTTP requests.Step 2: Compare options
Only To add extra information like authentication tokens or content type correctly describes headers' purpose; others describe different concepts.Final Answer:
To add extra information like authentication tokens or content type -> Option BQuick Check:
Headers add info = A [OK]
Hint: Headers carry extra info like tokens, not URL or method [OK]
Common Mistakes:
- Confusing headers with URL parameters
- Thinking headers change HTTP method
- Assuming headers handle response data
2. Which of the following is the correct way to add a header named
Authorization with value Bearer token123 using Angular's HttpHeaders?easy
Solution
Step 1: Recall HttpHeaders usage
HttpHeaders is immutable; usesetmethod to add headers.Step 2: Check each option
Only new HttpHeaders().set('Authorization', 'Bearer token123') usesnew HttpHeaders().set()correctly; others are invalid syntax or methods.Final Answer:
new HttpHeaders().set('Authorization', 'Bearer token123') -> Option AQuick Check:
Use set() on new HttpHeaders() = B [OK]
Hint: Use new HttpHeaders().set() to add headers [OK]
Common Mistakes:
- Trying to pass headers directly to constructor
- Using non-existent methods like append or add
- Not creating a new HttpHeaders instance first
3. Given the code below, what will be the final URL requested?
const params = new HttpParams().set('page', '2').set('sort', 'name');
this.http.get('/api/items', { params }).subscribe();medium
Solution
Step 1: Understand HttpParams chaining
Eachsetreturns a new HttpParams with added param; chaining adds both params.Step 2: Determine param order
Params appear in order set:page=2thensort=name.Final Answer:
/api/items?page=2&sort=name -> Option DQuick Check:
Params chained = URL with both params in order [OK]
Hint: Chained set() adds params in order to URL [OK]
Common Mistakes:
- Assuming only last set param remains
- Ignoring param order in URL
- Forgetting to pass params in request options
4. Identify the error in this Angular HTTP request code:
const headers = new HttpHeaders();
headers.set('Content-Type', 'application/json');
this.http.post('/api/data', body, { headers }).subscribe();medium
Solution
Step 1: Understand HttpHeaders immutability
HttpHeaders methods likesetreturn new instances; original is unchanged.Step 2: Analyze code behavior
Headers remain empty becausesetresult is not assigned back.Final Answer:
HttpHeaders is immutable; set() does not change original headers -> Option CQuick Check:
HttpHeaders immutable = assign set() result [OK]
Hint: Assign set() result to headers variable [OK]
Common Mistakes:
- Not assigning set() result back
- Assuming headers object changes in place
- Confusing HttpHeaders with plain objects
5. You want to send a GET request with headers
{ 'Authorization': 'Bearer abc123' } and query params { 'filter': 'active', 'limit': '10' }. Which code correctly sets both headers and params in Angular?hard
Solution
Step 1: Check header creation
HttpHeaders constructor accepts a plain object like{ Authorization: 'Bearer abc123' }for initial headers.Step 2: Check params creation
HttpParams constructor accepts{ fromObject: { filter: 'active', limit: '10' } }to set multiple params at once.Step 3: Verify request call
Bothheadersandparamsare passed correctly in the request options{ headers, params }.Final Answer:
Use HttpHeaders({ Authorization: 'Bearer abc123' }) and HttpParams({ fromObject: { filter: 'active', limit: '10' } }) -> Option AQuick Check:
Use constructors with objects for headers and params = C [OK]
Hint: Use HttpHeaders({}) and HttpParams({fromObject:{}}) for multiple values [OK]
Common Mistakes:
- Wrong constructor arguments or plain objects without proper instances
- Not assigning set() result due to immutability
- Using non-existent methods like add()
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
