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
MediumPut 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>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
1Meet Angular
Angular in ActionA Standalone ComponentComponent FieldsTypeScript in ComponentsRecap: Meet Angular7Forms and Validation
Two-Way BindingNormalizing Form TextSubmitting a FormValidation GuardsRecap: Forms2Template Bindings
Text InterpolationProperty BindingClass BindingStyle BindingRecap: Template Bindings5Conditions and Lists
Conditional ViewsRendering ListsEmpty List ViewsFiltering ViewsRecap: Control Flow6Reusable Components
Child ComponentsComponent InputsComponent OutputsContent ProjectionRecap: Components9Services and Shared State
Injecting a ServiceSharing Service StateService CommandsDerived Service StateRecap: Shared State