Global State with Angular Signals and the Power of Dependency Injection
Introduction
In Angular, signals are a great tool for state management and handling synchronous data. They aren’t limited to components; we can also use them in services to manage global state. This article demonstrates how to leverage signals and dependency injection (DI) in Angular to create a reusable global state management system.
Using Signals in Components
Let’s start with a simple example of a counter component that uses signals to manage its state.
In this example, we have a simple counter with increment and decrement functionality. However, this state is local to the component. Let’s move this state to a service to manage it globally.
Moving State to an Injectable Service
We’ll create a service to handle the global state of the counter.
By moving the state to an injectable service, we make it reusable across different components. This is similar to custom hooks in other frameworks, allowing us to encapsulate and reuse our application logic.
Functional Approach to State Management
If you prefer a more functional approach, you can create a function to handle the state.
This approach works the same way but lacks the benefits of DI, such as easily mocking dependencies and decoupling our code.
Using Injection Tokens for State Management
We can combine the functional approach with DI by creating the counter as an injection token.
Adding More Complexity with Dependency Injection
Of course, you can get creative and inject additional dependencies to create more complex state management solutions. For example, you might want to fetch the counter value from an API:
By injecting HttpClient
, we can now fetch the initial counter value from an external API, further demonstrating the flexibility and power of combining signals with DI. Of course you can get creative here and inject some other deps to create a more complex state management
Conclusion
Using Angular signals and DI together allows us to create flexible, reusable, and decoupled global state management solutions. Whether you prefer a class-based or functional approach, leveraging these powerful features of Angular can significantly improve your application’s architecture.