Dependency Injection (DI) is a pivotal design pattern that empowers developers to decouple their code, facilitating easier reuse of classes and services.
In the context of Angular, DI plays a crucial role in supplying dependencies to components, directives, pipes, and other injectable classes, promoting a more modular and maintainable codebase.
Understanding Angular Injection Context
The Angular injection context is the runtime environment where the DI system operates, allowing the injection of dependencies into your classes and functions. It is accessible in several key places, which include:
Constructor of an Injectable Class: Dependencies can be injected directly into the constructor of an injectable class.
Factory Function for an InjectionToken: When using an InjectionToken, we can specify a factory function that provides the necessary dependency.
Factory Function for the useFactory Property of a Provider: Providers in Angular can utilize the useFactory property, which employs a factory function to supply dependencies.
Initializer for a Field in an Injectable Class: We can initialize a field within an injectable class, ensuring that it receives the required dependency.
Function Passed to runInInjectionContext: The runInInjectionContext function enables code execution within an injection context, ensuring that dependencies are available for injection.
The inject() function injects dependencies into our code within these contexts. The inject() function accepts the token of the dependency you intend to inject as its sole argument, ensuring that Angular's DI system can seamlessly provide the required dependencies.
Use runInInjectionContext for Special Cases: In scenarios where we need to inject dependencies into code that typically does not run within an injection context, the runInInjectionContext function comes in handy. It enables us to execute code within an injection context, ensuring that dependencies are available for injection.
Angular Signal equality functions
If we want to do a deep comparison instead of just comparing references, we can instruct Angular to do so by providing our comparison function.
Here is an example:
import _ from 'lodash';
const data = signal(['test'], {equal: _.isEqual});
// Even though this is a different array instance, the deep equality
// function will consider the values to be equal, and the signal won't
// trigger any updates.
data.set(['test']);
You can see that code in action on Stackblitz here: https://stackblitz.com/edit/stackblitz-starters-okiav9?file=src%2Fmain.ts
I hope you found it helpful. Thanks for reading. 🙏
Let's get connected! You can find me on:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
- Buy Me a Coffee: https://www.buymeacoffee.com/nhannguyendevjs
Top comments (0)