Difference between @Injectable and @Inject Decorators
Last Updated :
01 Apr, 2024
In Angular, decorators play an important role in defining and managing dependencies within the application. Two commonly used decorators are @Injectable
and @Inject
. While they both relate to dependency injection, they serve different purposes and are applied to different elements within an Angular application.
What are @Injectable Decorators ?
@Injectable
is a decorator in Angular used to mark a class as an injectable that allows it to be provided and injected as a dependency within other Angular components, services, or modules.
Syntax:
@Injectable({
providedIn: 'root',
})
export class ServiceClass {
constructor() {}
}
Features of @Injectable decorators
- Singleton Pattern: Creates a single instance of a service to be shared across the application.
- Reusability: Services are designed to encapsulate certain capabilities, making integration and reuse simple.
- Lazy Loading: Optimizes performance by loading services only when needed, reducing initial load times.
Steps to Create Angular Project
Step 1: Create a new Angular Project using the following command
ng new gfg-decorators
Step 2: Create a new service
ng generate service gfg
Folder Structure:

Dependencies:
"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}
Example:
JavaScript
// gfg.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class GfgService {
constructor() { }
greetUser(user: string): string {
return `Hello ${user} from GfgService`;
}
}
We created a method greetUser(user: string), which accepts the username as a parameter and will return a greeting message with the username.
Output:
The '@Injectable' decorator makes no apparent changes to itself. Instead, it acts as a label in Angular, which means that a particular class can be assigned to other parts of the code. As a result, you won't get any output if you only use '@Injectable'. It's more like telling Angular "Hey, this class is there to be used elsewhere!"
What are @Inject Decorators ?
@Inject
is a decorator used to specify the token (dependency) to be injected into a class constructor or a provider definition. It specifies dependencies explicitly for Angular's DI system when automatic resolution is not possible, helping to resolve dependencies based on the specified token.
Features of @Inject decorators
- Decoupling: Enables dependencies and components to be coupled less tightly.
- Parameter Injection: Injecting dependencies into constructors or methods without relying on TypeScript's type inference.
- Clearer Intent: Enhances readability by indicating which dependencies are being injected into a component or service.
Syntax:
export class MyComponent {
constructor(@Inject(ServiceClass) private myService: ServiceClass) {}
}
Now Create a new component:-
ng generate component gfgcomponent
Folder Structure:
A new component will be created in app folderExample:
HTML
<!-- gfgcomponent.component.html -->
<p>{{greetingMessage}}</p>
JavaScript
// gfgcomponent.component.ts
import { Component, Inject } from '@angular/core';
import { GfgService } from '../gfg.service';
@Component({
selector: 'app-gfgcomponent',
templateUrl: './gfgcomponent.component.html',
styleUrls: ['./gfgcomponent.component.css']
})
export class GfgcomponentComponent {
constructor(@Inject(GfgService) private gfgService: GfgService) { }
greetingMessage = "";
ngOnInit() {
this.greetingMessage = this.gfgService.greetUser("GFGUser")
}
}
- The GfgService is injected into the component using the @Inject decorator in the constructor.
- Next, we can use greetUser() method from GfgService, and we save the resultant greeting message in the greetingMessage variable.
- You can now access and see this welcome message in the HTML template of the component.
Output:
Output on browserDifference between @Injectable and @Inject decorators
Feature
| @Injectable Decorator
| @Inject Decorator
|
---|
Purpose
| Marks a class as eligible for dependency injection.
| Specifies a dependency token for manual injection.
|
Usage
| Applied to service classes or providers.
| Applied to constructor parameters to specify injection dependencies.
|
Dependency Scope
| Defines the metadata needed for DI resolution.
| Specifies the exact dependency to be injected.
|
Dependency Type
| Marks a class as a candidate for DI resolution.
| Directs DI to inject a specific dependency instance.
|
Example
| @Injectable({ providedIn: 'root' })
| constructor(@Inject(MyDependency) private dependency: MyDependency)
|
Conclusion
In summary, @Injectable
is used to mark a class as injectable, that allows it to be managed by Angular's dependency injection system, while @Inject
is used to specify the token (dependency) to be injected into a class constructor or a provider definition. Understanding the difference between these decorators is important for effectively managing dependencies and implementing dependency injection in Angular applications.
Similar Reads
Difference between declarations and entryComponents in AngularJS Declarations: These are the set of components, directives, and pipes (declares) that belong to the (this) module. These components are in the local scope (private visibility).Syntax:Â Â declarations: Array<Type | any[]>The set of selectors (directives, components, pipes) are declared:Â that are a
2 min read
Spring - Difference Between Dependency Injection and Factory Pattern Dependency Injection and Factory Pattern are almost similar in the sense that they both follow the interface-driven programming approach and create the instance of classes. A. Factory Pattern In Factory Pattern, the client class is still responsible for getting the instance of products by class getI
4 min read
Difference Between Dagger, Hilt, Koin and Pure Dependency Injection It is often an overwhelming task to choose the most suitable dependency injection framework for your project, as there are a variety of popular and widely used frameworks on the market. Dagger, Hilt, Koin, and Pure Dependency Injection are some of the most popular frameworks currently in use. What i
5 min read
What is the difference between declarations, providers, and import in NgModule? Let us first discuss about these terms: Declarations: Declarations are used to declare components, directives, pipes that belongs to the current module. Everything inside declarations knows each other.Declarations are used to make directives (including components and pipes) from the current module a
2 min read
Difference Between the Facade, Proxy, Adapter, and Decorator Design Patterns Understanding design patterns is crucial for software developers. Facade, Proxy, Adapter, and Decorator are key patterns that address different aspects of software design, from simplifying interfaces to enhancing functionality. This article explores their distinctions and practical applications in s
4 min read
Spring - Difference Between Inversion of Control and Dependency Injection Understanding the difference between Inversion of Control (IoC) and Dependency Injection (DI) is very important for mastering the Spring framework. Both concepts are closely related, they serve different purposes in the context of Spring. The main difference between IoC and DI is listed below:Invers
3 min read
What is the Difference between Constructor and ngOnInit in AngularJS ? Constructor: Constructor is the default method for a class that is created when a class is installed and ensures the proper execution of the roles in the class and its subsections. Angular are preferably the Dependency Injector (DI), analyzes the builder's components and when creating a new feature
3 min read
What are the differences between an Annotation and a Decorator in Angular? Although Annotations and Decorators both share the same @ symbol in Angular, they both are different language features. Annotations: These are hard-coded language feature. Annotations are only metadata set on the class that is used to reflect the metadata library. When user annotates a class, the co
3 min read
How To Use @Injectable Decorator In Angular? In Angular, the @Injectable decorator is used to mark a class as available for dependency injection. This allows Angular to create and manage instances of this class and inject it into other components, services, or other classes.In this article, we will see how to use the @Injectable decorator in a
3 min read
Spring Boot - Difference Between AOP and AspectJ Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se
3 min read