How do you create and use a service?
Model answer
Create a class with the @Injectable decorator, usually with providedIn: 'root' so Angular creates one shared instance for the whole app. Put the logic in methods. In a component, get it with inject(UserService) or a constructor parameter, then call its methods.
Example: a UserService with a getUsers() method that returns an HTTP call. Two components can both inject it and use the same code.
Tips
- Mention providedIn root and what singleton means.
Learn this topic
Angular Tutorial: Beginner to Advanced .
Sign in to add your own answer.
More questions
- What is Angular, and how is it different from AngularJS?
- What is a single-page application (SPA)?
- What does the Angular CLI do? Name some common commands.
- What is a standalone component, and why did Angular move away from NgModules?
- What is TypeScript, and why does Angular use it?
- Describe the structure of a basic Angular project.