Singleton or Not? Understanding Angular Services the Right Way

Angular services are a core feature of the framework, used to share data and functionality across components. Their primary purposes include:

  • Angular services are classes used to organize and share reusable logic across components.
  • They help keep components clean by handling data, business rules and API interactions.
  • Services use Angular’s dependency injection system, making them easy to share and test.
  • They can also act as lightweight state stores using signals, computed values and effects.

You create an Angular service by running a CLI command:
ng g s log
This command should scaffold the LogService as shown below:

import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class Log {
}

When you create a service in Angular, you encounter two key characteristics:

  1. Services are tree-shakeable
  2. Services are singletons

In this article, we will explore the truthfulness of these two behaviors in depth. Read on.

Are Angular Services Tree-Shakeable?

By default, Angular services are tree-shakeable. Tree-shaking is a dead code elimination technique that removes unused code from the final bundle, reducing application size and improving performance.

Angular tree-shakes a service and excludes it from the final bundle:

  1. If it is provided with providedIn option
  2. If it is not re-provided anywhere in the application using providers array
  3. If it is not used anywhere in the application

Read full article here – https://www.telerik.com/blogs/singleton-not-understanding-angular-services-right-way

I hope you find this article useful. Thanks for reading.

Published by Dhananjay Kumar

Dhananjay Kumar is founder of NomadCoder and ng-India

Leave a Reply

Discover more from Dhananjay Kumar

Subscribe now to keep reading and get access to the full archive.

Continue reading