Sub topic 11
Text, blob and arrayBuffer responses
Prerequisites and scope
This chapter assumes you can declare an httpResource, read value(), status() and error(), and make a request depend on signals. Earlier chapters covered those. Here you will learn what happens when the response body is not JSON, and which of the three variants to use.
By default, httpResource reads the response body as JSON. If the server sends plain text, an image or a PDF, the default call fails. Angular provides three variants for these cases: httpResource.text, httpResource.blob and httpResource.arrayBuffer.
The three variants
Each variant takes the same first argument as httpResource: a URL string, a request object, or a function that returns either one (or undefined). Each also takes the same options, such as defaultValue. Only the type of value() differs.
| Variant | `value()` type | Typical use | Column |
|---|---|---|---|
| `httpResource` | JSON, typed by you | API data | |
| `httpResource.text` | `string \ | undefined` | Plain text, CSV, Markdown, XML, HTML fragments |
| `httpResource.blob` | `Blob \ | undefined` | Images, PDFs, files to display or download |
| `httpResource.arrayBuffer` | `ArrayBuffer \ | undefined` | Raw bytes you want to inspect or decode yourself |
value() is undefined until the first response arrives, as with the JSON form. A defaultValue option removes undefined from the type.
Why the default call fails on non-JSON
Suppose /assets/notes.txt returns Buy milk. With a plain httpResource, Angular tries to parse the body as JSON. That parse fails, and the resource moves to the error status. The request itself succeeded, so the error can be misleading. If a resource reports an error on an endpoint that works in the browser, check the content type first.
import { httpResource } from '@angular/common/http';
// Wrong for a text file: the body is not valid JSON, so the resource ends in error.
export const wrong = httpResource(() => '/assets/notes.txt');
// Right: the body is read as a string.
export const right = httpResource.text(() => '/assets/notes.txt');Text responses
httpResource.text gives you the body as a string. It is a good fit when you want to parse the text yourself, for example CSV. Because value() is a signal, a computed can derive structured data from it. The derived value updates whenever the text changes.
import { Component, computed, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
@Component({
selector: 'app-csv-preview',
template: `
<select (change)="file.set($any($event.target).value)">
<option value="people.csv">People</option>
<option value="cities.csv">Cities</option>
</select>
@if (csv.isLoading()) {
<p>Loading…</p>
}
@if (csv.error()) {
<p>Could not load the file.</p>
}
<table>
@for (row of rows(); track $index) {
<tr>
@for (cell of row; track $index) {
<td>{{ cell }}</td>
}
</tr>
}
</table>
`,
})
export class CsvPreviewComponent {
file = signal('people.csv');
csv = httpResource.text(() => `/assets/${this.file()}`, { defaultValue: '' });
rows = computed(() =>
this.csv.hasValue()
? this.csv
.value()
.split('\n')
.filter((line) => line.trim() !== '')
.map((line) => line.split(','))
: [],
);
}Two details matter here. First, defaultValue: '' means the string methods never run on undefined. Second, hasValue() guards the read. In the error state, reading value() throws, so check hasValue() when a computed or effect reads it outside a template guarded by @if.
The naive CSV split above breaks on quoted commas. Use a real CSV parser for production data.
Blob responses
A Blob is a browser object that holds binary data and a MIME type. Use httpResource.blob when you want to show the data (an image) or let the user save it (a file download). A blob cannot be bound directly to an <img>. You first turn it into an object URL with URL.createObjectURL.
Object URLs hold the blob in memory until you release them with URL.revokeObjectURL. An effect with a cleanup callback fits this well. The cleanup runs before the effect runs again and when the component is destroyed.
import { Component, effect, inject, input, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
@Component({
selector: 'app-avatar',
template: `
@if (avatar.isLoading()) {
<p>Loading image…</p>
}
@if (avatar.error()) {
<p>Could not load the image.</p>
}
@if (imageUrl(); as url) {
<img [src]="url" alt="User avatar" width="96" height="96" />
}
`,
})
export class AvatarComponent {
userId = input.required<number>();
private sanitizer = inject(DomSanitizer);
avatar = httpResource.blob(() => `/api/users/${this.userId()}/avatar`);
imageUrl = signal<SafeUrl | null>(null);
constructor() {
effect((onCleanup) => {
if (!this.avatar.hasValue()) {
this.imageUrl.set(null);
return;
}
const url = URL.createObjectURL(this.avatar.value());
this.imageUrl.set(this.sanitizer.bypassSecurityTrustUrl(url));
onCleanup(() => URL.revokeObjectURL(url));
});
}
}This example writes a signal inside an effect, which needs Angular 19 or later. In earlier versions it needs the allowSignalWrites option.
When userId changes, the old request is cancelled and a new one starts. The effect then runs its cleanup for the previous URL, so memory does not accumulate as users click through avatars.
Downloads
For a download, you do not need an <img>. You can create an object URL, point an anchor at it and click it from code. The blob's type property tells you the MIME type the server declared, which helps you choose a file extension.
arrayBuffer responses
An ArrayBuffer is a fixed block of raw bytes. You cannot read it directly. You wrap it in a view such as Uint8Array or DataView. Use httpResource.arrayBuffer when your code needs the bytes themselves, for example to check a file signature, decode a custom binary format, or hand the data to a library such as an audio decoder.
import { Component, computed } from '@angular/core';
import { httpResource } from '@angular/common/http';
@Component({
selector: 'app-file-header',
template: `
@if (file.isLoading()) {
<p>Loading…</p>
}
@if (file.error()) {
<p>Could not load the file.</p>
}
@if (file.hasValue()) {
<p>Size: {{ size() }} bytes</p>
<p>First bytes (hex): {{ header() }}</p>
<p>Looks like a PNG: {{ isPng() ? 'yes' : 'no' }}</p>
}
`,
})
export class FileHeaderComponent {
file = httpResource.arrayBuffer(() => '/assets/logo.png');
size = computed(() => (this.file.hasValue() ? this.file.value().byteLength : 0));
private firstBytes = computed(() => {
if (!this.file.hasValue()) {
return new Uint8Array(0);
}
const buffer = this.file.value();
return new Uint8Array(buffer, 0, Math.min(8, buffer.byteLength));
});
header = computed(() =>
Array.from(this.firstBytes())
.map((b) => b.toString(16).padStart(2, '0'))
.join(' '),
);
isPng = computed(() => this.header() === '89 50 4e 47 0d 0a 1a 0a');
}The first eight bytes of every PNG file are 89 50 4e 47 0d 0a 1a 0a, so the check works without decoding the image.
Behavior shared with the JSON form
The variants differ only in how the body is read. Everything else works as in earlier chapters:
- A signal read inside the request function triggers a new request when it changes, and the previous in-flight request is cancelled.
- Returning
undefinedfrom the request function keeps the resource idle. reload()repeats the current request. While it runs, the status isreloadingand the previous value stays available.- Request objects can set
headers,paramsandmethod. Setting anAcceptheader is useful when a server returns different formats from the same URL. - Interceptors registered with
provideHttpClient(withInterceptors([...]))run for these requests too, because all variants go throughHttpClient. - A non-2xx status puts the resource in the
errorstate, whichever variant you use.
Common mistakes
- Using the JSON form for non-JSON bodies. The symptom is an error state although the network tab shows a 200 response. Switch to the matching variant.
- Reading
value()in an error state. It throws. UsehasValue()or read it inside an@ifthat has already excluded the error. - Forgetting to revoke object URLs. Each
createObjectURLcall keeps its blob alive. Create URLs in aneffectand revoke them in the cleanup. - Creating object URLs in a
computed. Acomputedhas no cleanup hook, so every recomputation leaks a URL. - Loading very large files into memory.
blobandarrayBufferhold the entire body. For large downloads, link directly to the file URL and let the browser handle it. - Expecting a stable
value()while the request changes. When the request signal changes, the resource goes toloadingandvalue()becomesundefined(ordefaultValue). Onlyreload()keeps the old value.
Exercise
A component declares report = httpResource(() => '/api/report.pdf') and always ends in the error state, although the browser loads the URL fine. Which variant should replace it if the component shows the report in an <iframe>, and what must the component do to avoid a memory leak?
Show answer
Use httpResource.blob, because a PDF is a binary file you display, not JSON. The plain call tries to parse the body as JSON, which fails. Convert the blob to an object URL with URL.createObjectURL inside an effect, and call URL.revokeObjectURL in the effect's cleanup callback so each old URL is released when the resource changes or the component is destroyed.
Exercise
You use httpResource.arrayBuffer(() => '/assets/data.bin'). Write a computed that returns the first byte as a number, or -1 while there is no value.
Show answer
firstByte = computed(() => this.data.hasValue() && this.data.value().byteLength > 0 ? new Uint8Array(this.data.value())[0] : -1); The hasValue() check avoids reading value() while the resource is loading or in error. The byteLength check avoids returning undefined for an empty buffer. The Uint8Array view is needed because an ArrayBuffer cannot be indexed directly.