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:
- Services are tree-shakeable
- 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:
- If it is provided with
providedInoption - If it is not re-provided anywhere in the application using
providersarray - 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.
Discover more from Dhananjay Kumar
Subscribe to get the latest posts sent to your email.