Sub topic 3
Reading Full Responses with observe and responseType
This chapter assumes you already have a TodoService that injects HttpClient, and that you know RxJS pipe and basic operators.
Reading Full Responses
By default, HttpClient emits only the parsed JSON body. Pass observe: 'response' to get an HttpResponse that also carries the status code and headers. Use responseType ('json', 'text', 'blob' or 'arraybuffer') when the body is not JSON.
getTodosWithHeaders(): Observable<HttpResponse<Todo[]>> {
return this.http.get<Todo[]>(this.baseUrl, { observe: 'response' });
}
downloadReport(): Observable<Blob> {
return this.http.get('/api/report.csv', { responseType: 'blob' });
}Functional Interceptors
An interceptor is a function that every request passes through. It is a good place for auth headers, logging and global error handling. HttpRequest objects are immutable, so you have to clone them to change them. Register interceptors with provideHttpClient(withInterceptors([authInterceptor])).
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = localStorage.getItem('access_token');
return next(token
? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } })
: req);
};Cancelling and Combining Requests
When you unsubscribe from an HTTP Observable, Angular cancels the request. switchMap relies on this: each new search term cancels the request that is still in flight. forkJoin waits for several requests to finish and emits all their results together.
results$ = this.search.valueChanges.pipe(
debounceTime(300),
switchMap(term => this.http.get<Todo[]>('/api/todos', { params: { q: term ?? '' } }))
);Passing Metadata with HttpContext
To give one request a per-request flag that an interceptor can read, use an HttpContextToken.
export const SKIP_AUTH = new HttpContextToken<boolean>(() => false);
this.http.get('/api/public', { context: new HttpContext().set(SKIP_AUTH, true) });
// In the interceptor: if (req.context.get(SKIP_AUTH)) return next(req);Tracking Progress
Set reportProgress: true and observe: 'events' to receive progress events, then filter them by HttpEventType.
this.http.post('/api/upload', formData, { reportProgress: true, observe: 'events' })
.subscribe(event => {
if (event.type === HttpEventType.UploadProgress && event.total) {
console.log(Math.round((100 * event.loaded) / event.total) + '%');
}
});Testing HTTP Services
Provide provideHttpClient() and then provideHttpClientTesting(). Next, subscribe to the service method and catch the request with HttpTestingController.expectOne(url). Answer it with req.flush(mockData), and call verify() in afterEach so the test fails if any request was left unanswered.
Exercise
A typeahead fires a request on every keystroke and old results sometimes overwrite new ones. Which operator fixes this, and why?
Show answer
switchMap. It unsubscribes from the previous inner Observable when a new term arrives, which cancels the stale HTTP request, so only the latest response is emitted.
Exercise
How would you let one request skip the auth interceptor without changing its URL?
Show answer
Define an HttpContextToken such as SKIPAUTH, set it to true in that request's context option, and have the interceptor check req.context.get(SKIPAUTH) and call next(req) unchanged.