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:
Example:
<!-- gfgcomponent.component.html -->
<p>{{greetingMessage}}</p>
// 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:
Difference between @Injectable and @Inject Decorators
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.
Table of Content
- What are @Injectable Decorators ?
- What are @Inject Decorators ?
- Difference between @Injectable and @Inject decorators
- Conclusion
Contact Us