How do you create and use a service?

Angular basics · Freshers

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

Learn this topic

Angular Tutorial: Beginner to Advanced .

Sign in to add your own answer.

More questions