@abortor/angular
v0.1.4
Published
Angular integration for `@abortor/core`, providing scoped cancellation tied to Angular’s lifecycle.
Maintainers
Readme
@abortor/angular
Angular integration for @abortor/core, providing scoped cancellation tied to Angular’s lifecycle.
Features
- Scoped automatic cancellation: Use
injectAbortScope()to get aScopethat automatically disposes when the component (or service) is destroyed. - Root and child scope support: Offer
provideAbortor()at app level, theninjectRootedAbortScope()for per-component/sub-context scoping. - Perfect for RxJS and HttpClient: Works smoothly with
takeUntilDestroyedand gives you fetch-like cancellation viasignal.
Installation
npm install @abortor/angularSupports Angular 16–20 and RxJS 7+. Make sure your project also depends on
@abortor/core.
Quick Start
Provide a root scope in your app:
import { bootstrapApplication } from "@angular/platform-browser";
import { provideRouter } from "@angular/router";
import { provideAbortor } from "@abortor/angular";
import { AppComponent } from "./app.component";
import { appRoutes } from "./app.routes";
bootstrapApplication(AppComponent, {
providers: [
provideRouter(appRoutes),
provideAbortor({ label: "root-scope" }),
],
});Inject and use a scoped cancellation in a component:
import { Component, inject, DestroyRef, signal } from '@angular/core';
import { injectRootedAbortScope } from '@abortor/angular';
@Component({...})
export class UsersComponent {
private readonly destroyRef = inject(DestroyRef);
private readonly scope = injectRootedAbortScope('UsersComponent');
users = signal<any[]>([]);
error = signal<string | null>(null);
async reload() {
const req = this.scope.child({ label: 'users:reload' });
try {
const res = await req.fetch('/api/users', {
signal: (AbortSignal as any).timeout?.(10000),
});
if (!res.ok) throw new Error(res.statusText);
if (req.signal.aborted) return;
this.users.set(await res.json());
} catch (e: any) {
if (!['AbortError', 'TimeoutError'].includes(e.name)) {
this.error.set(e.message || String(e));
}
} finally {
req.dispose();
}
}
}API Overview
provideAbortor(opts?): Registers a rootScopevia Angular DI.injectAbortScope(opts?): Creates a scope tied to the currentDestroyRef.injectRootedAbortScope(label?): LikeinjectAbortScope, but falls back to the root scope if provided.
Why It Matters
- Avoids manual
AbortControllercleanup in Angular constructs. - Works smoothly with built-in lifecycle (
DestroyRef) and router cancellation patterns. - Adds timeout, hierarchy, and diagnostics capabilities on top of browser APIs.
