📖 Scenario: You are building a simple Angular service to fetch user data from a server. The server requires a custom header for authentication and a query parameter to specify the user ID.
🎯 Goal: Create an Angular service method that sends an HTTP GET request with custom headers and query parameters.
📋 What You'll Learn
Create an Angular service with HttpClient injected
Add a custom header named Authorization with value Bearer token123
Add a query parameter named userId with value 42
Use HttpParams and HttpHeaders to set params and headers
Send the GET request to https://api.example.com/users
💡 Why This Matters
🌍 Real World
APIs often require headers for authentication and query parameters to filter data. This project shows how to set them in Angular HTTP requests.
💼 Career
Knowing how to set headers and params in Angular services is essential for frontend developers working with REST APIs.
Progress0 / 4 steps
1
Create the Angular service and import HttpClient
Create an Angular service class named UserService and inject HttpClient in the constructor. Import HttpClient from @angular/common/http.
Angular
Hint
Remember to import HttpClient and add it to the constructor for dependency injection.
2
Create HttpHeaders and HttpParams variables
Inside the UserService class, create a variable named headers of type HttpHeaders with the header Authorization set to Bearer token123. Also create a variable named params of type HttpParams with the parameter userId set to 42. Import HttpHeaders and HttpParams from @angular/common/http.
Angular
Hint
Use new HttpHeaders().set() and new HttpParams().set() to create headers and params.
3
Create a method to send GET request with headers and params
Add a method named getUserData in UserService that returns the result of this.http.get to URL 'https://api.example.com/users' with the headers and params you created.
Angular
Hint
Use this.http.get with an options object containing headers and params.
4
Add return type and complete the service
Add the return type Observable<any> to the getUserData method. Import Observable from rxjs. This completes the Angular service for fetching user data with headers and params.
Angular
Hint
Import Observable and add : Observable<any> after the method name.
Practice
(1/5)
1. What is the main purpose of setting headers in an Angular HTTP request?
easy
A. To change the URL of the request
B. To add extra information like authentication tokens or content type
C. To modify the HTTP method (GET, POST, etc.)
D. To handle the response data format
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 B
Quick 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
A. new HttpHeaders().set('Authorization', 'Bearer token123')
B. new HttpHeaders('Authorization', 'Bearer token123')
C. HttpHeaders.append('Authorization', 'Bearer token123')
D. HttpHeaders.add('Authorization', 'Bearer token123')
Solution
Step 1: Recall HttpHeaders usage
HttpHeaders is immutable; use set method to add headers.
Step 2: Check each option
Only new HttpHeaders().set('Authorization', 'Bearer token123') uses new HttpHeaders().set() correctly; others are invalid syntax or methods.
Final Answer:
new HttpHeaders().set('Authorization', 'Bearer token123') -> Option A
Quick 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?
A. Headers must be plain object, not HttpHeaders instance
B. Missing import for HttpHeaders
C. HttpHeaders is immutable; set() does not change original headers
D. post() method requires params object
Solution
Step 1: Understand HttpHeaders immutability
HttpHeaders methods like set return new instances; original is unchanged.
Step 2: Analyze code behavior
Headers remain empty because set result is not assigned back.
Final Answer:
HttpHeaders is immutable; set() does not change original headers -> Option C
Quick 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
A. const headers = new HttpHeaders({ Authorization: 'Bearer abc123' });
const params = new HttpParams({ fromObject: { filter: 'active', limit: '10' } });
this.http.get('/api/users', { headers, params }).subscribe();