Overview
TheLoadingService manages the application’s loading state, tracking active HTTP requests and providing an observable stream that components can subscribe to. It works in conjunction with the LoadingInterceptor to automatically show and hide loading indicators.
Location: src/app/core/services/loading.service.ts
Properties
loading$
true when loading is active and false when all requests are complete. Components subscribe to this to show/hide loading indicators.
requestsInFlight
Methods
show()
Increments the request counter and emits a loading state oftrue.
Signature:
- Increments
requestsInFlightby 1 - Emits
trueto theloading$observable - Called automatically by the
LoadingInterceptorwhen an HTTP request starts
hide()
Decrements the request counter and emitsfalse only when all requests are complete.
Signature:
- Decrements
requestsInFlightby 1 (minimum value is 0) - Only emits
falsetoloading$whenrequestsInFlightreaches 0 - Called automatically by the
LoadingInterceptorwhen an HTTP request completes
Usage in Components
Basic Loading Indicator
Using Loading State in Component Logic
Integration with LoadingInterceptor
TheLoadingService is automatically integrated with HTTP requests through the LoadingInterceptor.
Interceptor Location: src/app/core/interceptors/loading.interceptor.ts
How It Works
- When an HTTP request starts, the interceptor calls
loadingService.show() - The request counter increments and
loading$emitstrue - When the request completes (success or error),
finalize()callsloadingService.hide() - The request counter decrements
- When all requests are done (counter reaches 0),
loading$emitsfalse
Registering the Interceptor
Observable Pattern
The service uses RxJSBehaviorSubject to manage state:
BehaviorSubjectprovides the current value immediately to new subscribers- Initial state is
false(not loading) - Private
_loadingsubject prevents external code from directly emitting values - Public
loading$observable allows components to subscribe safely
Handling Multiple Concurrent Requests
The service correctly handles multiple simultaneous HTTP requests:hide() method uses Math.max() to prevent negative values:
Complete Example
Implementation Details
- The service is provided in the root injector (
providedIn: 'root') - Uses RxJS
BehaviorSubjectfor reactive state management - Automatically integrates with all HTTP requests via the interceptor
- Handles concurrent requests correctly with a counter
- No manual intervention needed - works automatically with
HttpClient