Angular Services

Sophie Andriamahenintsoa
2 min readMay 25, 2021

--

Angular services are singleton objects that get instantiated only once during the lifetime of an application. They contain methods that maintain data throughout the life of an application, i.e. data does not get refreshed and is available all the time. The main objective of a service is to `organize` and `share` business logic, models, or data and functions with different components of an Angular application.

Dependency injection

Angular Services are usually implemented through `dependency injection`. When we talk about an injectable service class, we’re simply talking about common, service-oriented code that can be reused between separate components.

Singleton services

A singleton service is a service for which only one instance exists in an app.

An example of when to use services would be to `transfer` data from one controller to another custom service.

Providing a singleton service:

There are two ways to make a service a singleton in Angular:

  • Set the providedIn property of the @Injectable() to “root”.
  • Include the service in the AppModule or in a module that is only imported by the AppModule

Services at global or root level

`Global services` need to create at the `root` or in a `shared folder` in your application. This creates a single, shared instance of that service that’s `shared` by any and all components that want to use it.

Services at component level

Here, the `service` will only be used within one component within application, we should make sure that your service is only available where strictly necessary.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response