Sub topic 9
Reading Full Responses with observe and responseType
By default, HttpClient gives you only the parsed JSON body of a response. Usually that is all you need. Sometimes the body is not enough. A paginated API may put the total item count in a header. A file endpoint returns binary data, and a health check returns plain text. This chapter covers the two request options that control this: observe, which decides how much of the response you get, and responseType, which decides how the body is parsed.
This chapter assumes you have already built the typed TodoService from earlier chapters, know how HttpClient.get<T>() infers its return type, and can use pipe with map and catchError.
The two options
The two options answer different questions:
| Option | Question it answers | Values | Default |
|---|---|---|---|
| `observe` | How much of the HTTP exchange should the Observable emit? | `'body'`, `'response'`, `'events'` | `'body'` |
| `responseType` | How should the response body be parsed? | `'json'`, `'text'`, `'blob'`, `'arraybuffer'` | `'json'` |
You can set them independently. Every request method accepts both, including get, post, put, patch, delete and request. The combination you pick changes the static return type of the call, because HttpClient defines a separate TypeScript overload for each pair.
Reading status and headers with observe: 'response'
With observe: 'response', the Observable emits a single HttpResponse<T> object instead of the bare body. That object has these fields:
| Property | Type | Meaning | Column |
|---|---|---|---|
| `body` | `T \ | null` | The parsed body. It is `null` when the server sent no body. |
| `status` | `number` | The HTTP status code, for example `200` or `204`. | |
| `statusText` | `string` | The reason phrase. HTTP/2 servers often leave it empty. | |
| `headers` | `HttpHeaders` | Response headers. Lookup ignores case. | |
| `url` | `string \ | null` | The final URL after any redirects. |
| `ok` | `boolean` | `true` when the status is in the 200–299 range. |
The most common reason to read the full response is pagination metadata. The service below returns a page of todos along with the total count, which the server sends in an X-Total-Count header:
// todo.service.ts
import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpParams, HttpResponse } from '@angular/common/http';
import { Observable, map } from 'rxjs';
export interface Todo {
id: number;
title: string;
completed: boolean;
}
export interface TodoPage {
items: Todo[];
total: number;
}
@Injectable({ providedIn: 'root' })
export class TodoService {
private readonly http = inject(HttpClient);
private readonly baseUrl = '/api/todos';
getTodosWithHeaders(): Observable<HttpResponse<Todo[]>> {
return this.http.get<Todo[]>(this.baseUrl, { observe: 'response' });
}
getTodoPage(page: number, pageSize = 20): Observable<TodoPage> {
const params = new HttpParams().set('page', page).set('pageSize', pageSize);
return this.http
.get<Todo[]>(this.baseUrl, { params, observe: 'response' })
.pipe(
map(response => {
const items = response.body ?? [];
const header = response.headers.get('X-Total-Count');
const total = header !== null ? Number(header) : items.length;
return { items, total };
})
);
}
}getTodosWithHeaders exposes the raw HttpResponse. Callers can use it like this:
this.todoService.getTodosWithHeaders().subscribe(response => {
const total = response.headers.get('X-Total-Count');
console.log(response.status, total, response.body);
});getTodoPage is usually the better design. It unpacks the response inside the service, so components receive a plain domain object and never deal with HTTP types. Keep HttpResponse at the service boundary unless the caller really needs the status or headers.
The CORS header trap
If your API runs on a different origin from the app, response.headers.get('X-Total-Count') can return null even though the header is plainly visible in the browser's Network tab. Browsers expose only a short list of "safelisted" response headers to JavaScript on cross-origin requests: Cache-Control, Content-Language, Content-Length, Content-Type, Expires, Last-Modified and Pragma. Any other header must be listed by the server in Access-Control-Expose-Headers:
Access-Control-Expose-Headers: X-Total-Count, Content-DispositionYou cannot fix this in Angular. It is a server configuration change. A dev-server proxy hides the problem because it makes requests same-origin, so the bug often appears only after deployment.
Choosing a body parser with responseType
responseType tells HttpClient how to read the body. With 'json', the default, the body is passed through JSON.parse, and the result is cast to your generic type T. The other values skip JSON parsing:
| `responseType` | Body type | Typical use |
|---|---|---|
| `'json'` | `T` (generic, unchecked) | REST APIs |
| `'text'` | `string` | Plain-text endpoints, CSV, HTML fragments, raw JSON you want to validate yourself |
| `'blob'` | `Blob` | File downloads, images, PDFs |
| `'arraybuffer'` | `ArrayBuffer` | Binary protocols, data you will decode byte by byte |
Text responses
// Inside TodoService
getServerVersion(): Observable<string> {
return this.http.get('/api/version', { responseType: 'text' });
}Notice that there is no <string> type argument. The overloads for 'text', 'blob' and 'arraybuffer' are not generic, because the body type is fixed. Writing this.http.get<string>(url, { responseType: 'text' }) fails to compile. TypeScript considers only the generic overloads, and those require responseType to be 'json'. The error reads like an overload mismatch, which confuses many people the first time they see it.
Downloading a file
Binary downloads combine both options. You need the Blob body, and you usually want the file name from the Content-Disposition header:
// report.service.ts
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, map } from 'rxjs';
export interface DownloadedFile {
blob: Blob;
fileName: string;
}
@Injectable({ providedIn: 'root' })
export class ReportService {
private readonly http = inject(HttpClient);
downloadReport(id: number): Observable<DownloadedFile> {
return this.http
.get(`/api/reports/${id}`, { observe: 'response', responseType: 'blob' })
.pipe(
map(response => {
const disposition = response.headers.get('Content-Disposition') ?? '';
const match = /filename="?([^";]+)"?/i.exec(disposition);
return {
blob: response.body ?? new Blob(),
fileName: match ? match[1] : `report-${id}.pdf`
};
})
);
}
}
export function saveFile({ blob, fileName }: DownloadedFile): void {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = fileName;
link.click();
URL.revokeObjectURL(url);
}A component calls this.reportService.downloadReport(7).subscribe(saveFile). The revokeObjectURL call releases the memory the browser holds for the object URL. If you skip it, every download leaks the file's size until the page unloads.
Options must keep their literal types
The overloads select a return type based on the literal values 'response' and 'blob'. If you build the options object in a variable, TypeScript widens those values to string, and no overload matches:
// Does not compile: observe is inferred as string
const options = { observe: 'response' };
this.http.get<Todo[]>('/api/todos', options);There are three fixes, from most to least common:
- Write the options inline in the call, as the earlier examples do.
- Add
as constto keep the literals:const options = { observe: 'response' } as const;. - Annotate the property type:
const options: { observe: 'response' } = { observe: 'response' };.
The same rule applies to responseType. This matters most when a shared helper builds options for several calls.
Errors and edge cases
Error bodies follow responseType
When the server responds with an error status, HttpClient still parses the error body with the responseType you asked for. With responseType: 'blob', a JSON error such as {"message": "Report not found"} arrives as a Blob in HttpErrorResponse.error. To read it, convert it back to text:
import { HttpErrorResponse } from '@angular/common/http';
import { Observable, catchError, from, switchMap, throwError } from 'rxjs';
// Inside ReportService
downloadReportBlob(id: number): Observable<Blob> {
return this.http.get(`/api/reports/${id}`, { responseType: 'blob' }).pipe(
catchError((error: HttpErrorResponse) => {
if (error.error instanceof Blob) {
return from(error.error.text()).pipe(
switchMap(text => throwError(() => new Error(text || error.message)))
);
}
return throwError(() => error);
})
);
}observe: 'response' does not catch errors
A common misreading is that observe: 'response' lets you inspect 4xx and 5xx statuses in subscribe's next handler. It does not. Non-2xx responses still go to the error channel as HttpErrorResponse, which carries its own status and headers. The HttpResponse you receive in the next handler always has ok === true.
Empty bodies
A 204 No Content response, or a 200 with an empty body, produces body: null under 'json' and '' under 'text'. If the server sends a non-empty body that is not valid JSON while you requested 'json', the request fails with an HttpErrorResponse whose status is the successful status code, often 200. When you see a "failed" request with status 200, the cause is usually a parse error, for example an HTML error page returned by a proxy.
observe: 'events'
observe: 'events' emits every stage of the request as an HttpEvent. That includes the sent event, the response headers, any progress events, and the final HttpResponse. Its main use is tracking upload and download progress, which the chapter "Tracking Upload and Download Progress" covers.
Exercise
A cross-origin API returns a Link header with pagination URLs. Your code reads response.headers.get('Link') with observe: 'response' and always gets null, but the Network tab shows the header. What is wrong, and where is the fix?
Show answer
Link is not a CORS-safelisted response header, so the browser hides it from JavaScript on cross-origin requests. The server must add Access-Control-Expose-Headers: Link to its responses. Nothing in the Angular code needs to change.
Exercise
Why does this.http.get<string>('/api/version', { responseType: 'text' }) fail to compile, and how do you fix it?
Show answer
The responseType: 'text' overload is not generic because its body type is always string. With a type argument, TypeScript considers only the generic overloads, and those require responseType to be 'json', so no overload matches. Remove the type argument. The call this.http.get('/api/version', { responseType: 'text' }) returns Observable<string>.
Exercise
A teammate writes const opts = { observe: 'response', responseType: 'blob' }; this.http.get(url, opts); and gets "No overload matches this call". Give a one-line fix and explain why it works.
Show answer
Write const opts = { observe: 'response', responseType: 'blob' } as const;. Without as const, TypeScript widens both properties to string, and the overloads only accept the literal values. With as const, the properties keep the types 'response' and 'blob', so the overload returning Observable<HttpResponse<Blob>> matches.