Injecting a Service
Part of the Fundamentals section of Coddy's Angular journey. Lesson 41 of 55.
A service separates reusable state or behavior from a particular view. Injectable with providedIn root makes the service available through Angular's root injector.
@Injectable({providedIn:"root"})
class Rates { fee=4; total(n:number){return n+this.fee} }
// Component field: rates=inject(Rates);
// Template: <p>{{rates.total(6)}}</p>Call inject with the service class in a component field initializer. Angular supplies the service instance. Keeping calculations in a service lets multiple views use the same rules without repeating them.
Challenge
MediumImplement TicketRates as a root-provided service. Tickets cost 7 each. Inject it into the component and show its total for the current quantity, starting at 1. More increases quantity.
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