Consider this Angular service method that makes an HTTP GET request:
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
getData() {
const headers = new HttpHeaders().set('Authorization', 'Bearer token123');
const params = new HttpParams().set('page', '2').set('limit', '10');
return this.http.get('/api/items', { headers, params });
}Which headers and query parameters will be included in the request?
Look at how HttpHeaders and HttpParams are set with set method.
The HttpHeaders object sets the 'Authorization' header with the exact string 'Bearer token123'. The HttpParams object sets two query parameters: 'page' with value '2' and 'limit' with value '10'. These are sent with the GET request.
Given the need to add two headers: 'Content-Type' as 'application/json' and 'Accept' as 'application/json', which code snippet correctly creates the HttpHeaders object?
Remember that HttpHeaders is immutable and methods return new instances.
Option A chains set calls correctly, each returning a new HttpHeaders instance with the added header. Option A works but is less common. Option A uses append which adds multiple values for the same header, not needed here. Option A calls set on the original object without reassigning, so the second header is not added.
Look at this code snippet:
let params = new HttpParams();
params.set('search', 'books');
params.set('sort', 'asc');
this.http.get('/api/products', { params }).subscribe();Why are the query parameters missing in the request?
Check how HttpParams methods work regarding immutability.
HttpParams is immutable. Calling set returns a new HttpParams instance with the added parameter. The original params variable remains unchanged. The code should reassign the result of set back to params.
Consider this code:
let headers = new HttpHeaders();
headers = headers.set('X-Custom', '123');
headers.set('Authorization', 'token');What headers will be sent if headers is used in an HTTP request?
Remember that HttpHeaders methods return new instances and do not mutate the original.
The first set call assigns a new HttpHeaders instance with 'X-Custom' header to headers. The second set call creates a new instance with 'Authorization' header but does not assign it back, so headers remains unchanged from the first call.
Which statement best describes how Angular's HttpParams manages multiple values for the same query parameter key?
Think about how to add multiple values for the same parameter in a URL query string.
HttpParams supports multiple values for the same key by using the append method. This results in repeated keys in the URL query string, like ?key=value1&key=value2. The set method replaces existing values.