typescript 40 lines · 8 steps

Tracking HTTP loading state in Angular

A signal-backed counter and an interceptor combine to expose a global isLoading flag driven by in-flight requests.

Explained by highlit
1import { Injectable, signal, computed } from '@angular/core';
2import {
3 HttpInterceptorFn,
4 HttpContextToken,
5 HttpContext,
6} from '@angular/common/http';
7import { inject } from '@angular/core';
8import { finalize } from 'rxjs';
9 
10export const SKIP_LOADING = new HttpContextToken<boolean>(() => false);
11 
12export function skipLoading(): HttpContext {
13 return new HttpContext().set(SKIP_LOADING, true);
14}
15 
16@Injectable({ providedIn: 'root' })
17export class LoadingService {
18 private readonly activeRequests = signal(0);
19 
20 readonly isLoading = computed(() => this.activeRequests() > 0);
21 
22 start(): void {
23 this.activeRequests.update((count) => count + 1);
24 }
25 
26 stop(): void {
27 this.activeRequests.update((count) => Math.max(0, count - 1));
28 }
29}
30 
31export const loadingInterceptor: HttpInterceptorFn = (req, next) => {
32 if (req.context.get(SKIP_LOADING)) {
33 return next(req);
34 }
35 
36 const loading = inject(LoadingService);
37 loading.start();
38 
39 return next(req).pipe(finalize(() => loading.stop()));
40};
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Reference counting handles overlapping requests so the loading flag stays accurate under concurrency.
  2. 2A functional interceptor is the natural place to start and stop shared state around every request.
  3. 3An HttpContextToken lets individual requests opt out of cross-cutting behavior without touching the interceptor's core logic.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Tracking HTTP loading state in Angular — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code