The @Injectable
decorator provided by the Angular framework allows classes to be decorated and registered with Angular’s dependency injection system. When a class is decorated with @Injectable
, Angular creates and manages instances of that class, resolving its dependencies as needed.
When a class is marked with the @Injectable
decorator, it becomes eligible for constructor injection. Constructor injection is a form of dependency injection where the dependencies of a class are provided through its constructor parameters. The framework analyzes the constructor parameters of the decorated class and resolves their dependencies automatically.
Key takeaways:
The @Injectable
decorator allows services to be injected into components and other services.
@Injectable
can register services at different levels: root, module, or component, providing flexibility in service scope.
Using providedIn: 'root'
enables tree shaking, optimizing bundle size by excluding unused services.
@Injectable
enables constructor injection, simplifying the process of injecting dependencies into classes.
The decorator generates metadata that Angular uses to resolve dependencies at runtime.
Angular’s hierarchical injector system allows for more granular control over service instances.
To use @Injectable
, follow these steps:
Step 1: Create the service
First, we need to create a service class that we want to register. A service typically contains business logic, data retrieval, manipulation, or other functionality that can be shared across components. We can create a service using CLI by executing the following command: