Menu
CoddyTech

Service Commands

Part of the Fundamentals section of Coddy's Angular journey. Lesson 43 of 55.

A service can expose methods that enforce rules while keeping its writable state private. The example offers a read-only signal for views and a command that refuses to reduce stock below zero.

@Injectable({providedIn:"root"})
class Shelf {private value=signal(1); stock=this.value.asReadonly(); take(){this.value.update(n=>Math.max(0,n-1))}}
// take() is called twice.

Read-only means callers cannot use set or update on that exposed signal. It is not deep immutability for objects, so keep collection changes behind service methods too. Commands make the same rule apply from every caller.

challenge icon

Challenge

Medium

Put basket changes behind BasketStore commands. Start with 2 and expose a read-only count. Take removes one but never goes below zero.

Edit the supplied files. Press Run preview to refresh the preview after edits, then use Check or Run code to grade your work. Keep the requested element IDs.

Try it yourself

<!doctype html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="styles.css"></head><body><app-root></app-root><script type="module" src="main.ts"></script></body></html>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals