typescript 48 lines · 8 steps

Autosaving a form with RxJS in Angular

An Angular component turns form changes into a debounced, self-cleaning autosave pipeline with a live status signal.

Explained by highlit
1@Component({
2 selector: 'app-article-editor',
3 templateUrl: './article-editor.component.html',
4})
5export class ArticleEditorComponent implements OnInit, OnDestroy {
6 @Input() articleId!: string;
7 
8 readonly form = this.fb.nonNullable.group({
9 title: ['', Validators.required],
10 summary: [''],
11 body: [''],
12 });
13 
14 readonly saveState = signal<'idle' | 'saving' | 'saved' | 'error'>('idle');
15 
16 private readonly destroy$ = new Subject<void>();
17 
18 constructor(
19 private readonly fb: FormBuilder,
20 private readonly drafts: DraftService,
21 ) {}
22 
23 ngOnInit(): void {
24 this.form.valueChanges
25 .pipe(
26 filter(() => this.form.valid),
27 map(() => this.form.getRawValue()),
28 debounceTime(800),
29 distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b)),
30 tap(() => this.saveState.set('saving')),
31 switchMap((draft) =>
32 this.drafts.save(this.articleId, draft).pipe(
33 catchError(() => {
34 this.saveState.set('error');
35 return EMPTY;
36 }),
37 ),
38 ),
39 takeUntil(this.destroy$),
40 )
41 .subscribe(() => this.saveState.set('saved'));
42 }
43 
44 ngOnDestroy(): void {
45 this.destroy$.next();
46 this.destroy$.complete();
47 }
48}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Chaining RxJS operators lets you express debounce, dedupe, and cancellation as one declarative pipeline.
  2. 2switchMap plus catchError keeps a save stream alive by cancelling stale requests and swallowing errors without breaking the observable.
  3. 3A destroy Subject with takeUntil is a reliable pattern for tearing down subscriptions when a component is destroyed.

Related explainers

typescript
type CountdownState = {
  deadline: number;
  onTick: (remaining: number) => void;
  onComplete: () => void;

A countdown timer that survives reloads

persistence timers localstorage
Intermediate 10 steps
typescript
type QueuedRequest = {
  id: string;
  url: string;
  method: string;

A retry queue with exponential backoff

retry exponential-backoff persistence
Intermediate 10 steps
typescript
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';

How a JWT strategy authenticates in NestJS

authentication jwt passport
Intermediate 7 steps
typescript
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { BehaviorSubject, Observable, throwError } from 'rxjs';
import { catchError, filter, take, switchMap } from 'rxjs/operators';

Refreshing auth tokens in an Angular interceptor

http-interceptor token-refresh rxjs
Advanced 8 steps
python
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector
from django.core.cache import cache
from django.db.models import F
from django.http import JsonResponse

Ranked full-text search in Django

full-text-search debouncing caching
Advanced 9 steps
typescript
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';

How a GraphQL auth guard works in NestJS

authentication authorization jwt
Intermediate 7 steps

Share this explainer

Here's the card — post it anywhere.

Autosaving a form with RxJS in Angular — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code