Singleton Pattern
In Angular, the Singleton Pattern is often implemented using Angular services.
Angular services are singletons by default, meaning Angular creates only one instance of a service and shares it throughout the application.
This makes them ideal for managing shared state, performing common tasks, or encapsulating reusable functionality.
Here's an example of implementing a singleton service in Angular:
In this example:
@Injectable
decorator is used to mark the class as a service.providedIn: 'root'
option in the@Injectable
decorator ensures that Angular creates a single instance of the service for the entire application.The
MySingletonService
class contains some shared data (sharedData
) and methods to manipulate it.You can inject
MySingletonService
into any component, directive, or other service in your Angular application.
Here's how you would use the MySingletonService
in a component:
In this component:
We inject
MySingletonService
into the constructor.In the constructor, we initialize the
sharedData
property with the data retrieved from the service.The
updateSharedData()
method demonstrates how to update the shared data via the service.
By using Angular services, you're effectively utilizing the Singleton Pattern, ensuring that there's only one instance of the service throughout the Angular application.
Last updated