Sub topic 9
Reading Full Responses with observe and responseType
This chapter assumes you have already written the typed TodoService from earlier chapters and know how HttpClient.get<T>() returns an Observable<T>. It also assumes you know the basics of HTTP headers and status codes.
By default, HttpClient gives you only the parsed JSON body. That covers most calls. Some APIs put useful data outside the body, though. A paginated endpoint might send the total item count in a header, and a report endpoint might return a CSV file instead of JSON. The observe and responseType options let you handle both cases.
What the two options control
The two options control different things:
observedecides how much of the response you receive: only the body, the wholeHttpResponse, or the full stream ofHttpEventobjects.responseTypedecides how the body is parsed: as JSON, plain text, aBlob, or anArrayBuffer.
| Option | Value | Observable emits |
|---|---|---|
| `observe` | `'body'` (default) | The parsed body, typed `T` |
| `observe` | `'response'` | `HttpResponse<T>` with status, headers and body |
| `observe` | `'events'` | Every `HttpEvent<T>`, including progress events |
| `responseType` | `'json'` (default) | A parsed object |
| `responseType` | `'text'` | `string` |
| `responseType` | `'blob'` | `Blob` |
| `responseType` | `'arraybuffer'` | `ArrayBuffer` |
Reading status and headers with observe: 'response'
Pass observe: 'response' when you need the status code or a header along with the data:
import { HttpResponse } from '@angular/common/http';
// Inside TodoService
getTodosWithHeaders(): Observable<HttpResponse<Todo[]>> {
return this.http.get<Todo[]>(this.baseUrl, { observe: 'response' });
}
// Usage
this.todoService.getTodosWithHeaders().subscribe(response => {
const total = response.headers.get('X-Total-Count');
console.log(response.status, total, response.body);
});The generic parameter still describes the body, so response.body is typed Todo[] | null. The null is real: a 204 No Content reply has no body. Check for it before you use the body.
response.headers is an HttpHeaders instance. Its get() method returns a string | null, so convert numeric headers yourself, for example with Number(total).
Non-JSON bodies with responseType
When the body is not JSON, set responseType. Angular then skips JSON parsing, and the return type changes to match:
// Inside TodoService
exportCsv(): Observable<string> {
return this.http.get('/api/todos/export', { responseType: 'text' });
}
downloadAttachment(id: number): Observable<Blob> {
return this.http.get(`${this.baseUrl}/${id}/attachment`, {
responseType: 'blob'
});
}These calls have no generic parameter, because the body type is fixed (string or Blob). If you write get<string>(url, { responseType: 'text' }), TypeScript reports an error.
You can combine the two options. { observe: 'response', responseType: 'blob' } gives you an HttpResponse<Blob>, so you can read a Content-Disposition header to get the file name while you download the file.
The literal-type gotcha
HttpClient.get has many overloads, and TypeScript picks one by looking at the literal values of observe and responseType. If you build the options object in a separate variable, TypeScript widens those values to string, and no overload matches:
// Fails: observe is widened to string
const opts = { observe: 'response' };
// this.http.get<Todo[]>(this.baseUrl, opts);
// Works: keep the literal type
const typedOpts = { observe: 'response' as const };
this.http.get<Todo[]>(this.baseUrl, typedOpts);Write the options inline, or add as const, and the call compiles with the right return type.
The third observe value, 'events', emits progress events during uploads and downloads. It is covered in the chapter on tracking progress.
Exercise
What type does this.http.get('/api/report', { responseType: 'text', observe: 'response' }) return, and why would this.http.get<string>('/api/report', { responseType: 'text' }) fail to compile?
Show answer
It returns Observable<HttpResponse<string>>. The second call fails because the text overloads have no generic type parameter. The body type is always string, so passing <string> matches no overload.
Exercise
Your service reads X-Total-Count with observe: 'response'. The header shows in the browser's network tab, but headers.get('X-Total-Count') returns null. The API runs on a different origin. What is wrong?
Show answer
The browser hides the custom header from JavaScript because of CORS. The server must send Access-Control-Expose-Headers: X-Total-Count so the browser makes the header readable.