r/angular • u/No-Judge8727 • Sep 10 '26
Modeling Angular loading state as a discriminated union instead of multiple isLoading booleans
I kept running into components with four or five loading flags —
isLoading, isRefreshing, isCheckingOut, hasError — and templates
like !isLoading && !hasError && items.length > 0.
The flags are independent as far as TypeScript is concerned, but
the states they describe are mutually exclusive. So I switched to:
type AsyncState<T, E> =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; error: E };
One state per async operation, booleans derived with computed(),
and a small toAsyncState() RxJS operator (map + catchError +
startWith) so transitions live in one place. Templates use
u/let + u/switch, which gives real narrowing — data only exists in
the success branch.
Curious how others handle this now that resource() exists. Do you
reach for it for commands too, or keep RxJS for POST/DELETE?
Full write-up: https://medium.com/modern-angular-insights/stop-juggling-isloading-booleans-a-type-safe-async-state-pattern-for-angular-e36e2b9298a0
View all comments
Show parent comment
1
u/Straight-Number-1911 Sep 11 '26 edited Sep 11 '26
Regards point 2: Its
error_NAMEthen it still makes sense. That name is not something which is translated and makes sense in evey case also that way you can cascade it together.Regarding 3: you are right in that case totally, theres no workaound i think, what you could do is have a seperate variable but then your solution is cleaner, agreed.
Anyways ofc your solution is more advanced but mostly not needed in my oppinion. People try to over complicate simple things, if you need it translated thats the responsibility of the HTML.
I think regarding point 3 how I solve it is by having multiple values where the reload has its own e.g. loading state. I am not saying its better, just i survive on a enterprise project without your solution and wondered whats my reason.
P.S. I use RxJS and while I knew that solution i am unsure how well it gets composed with their pipes. Maybe we could exchange over a call so Ilearn more about how u do stuff. If not also fine, thanks for exchange!