How To Use @Injectable Decorator In Angular?
Last Updated :
24 Sep, 2024
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 an Angular application, including a setup example and sample code.
How Does The @Injectable Decorator Work?
The @Injectable decorator can be configured with optional metadata. By default, when you create a service in Angular, you don’t need to pass any arguments to @Injectable. However, there are cases where you might need to specify certain providers explicitly.
The most common configuration is:
@Injectable({
providedIn: 'root'
})
This means that the service will be available throughout the application, at the root level, and Angular will create only one instance of the service (singleton). You can also limit the availability of the service to a specific module if needed.
Steps To Use @Injectable Decorator In Angular
Step 1: Set Up a New Angular Project
If you don't have an Angular project set up yet, you can create one using the Angular CLI.
npm install -g @angular/cli
ng new my-angular-app
cd my-angular-app
Step 2: Create a Service with @Injectable
To use the @Injectable decorator, you'll typically create a service. Let's generate a new service using the Angular CLI.
ng generate service my-service
This will create two files:
- my-service.service.ts
- my-service.service.spec.ts (for testing)
Folder Structure
Folder StructureDependencies
"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",
"lodash": "^4.17.21",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}
Step 3: Define a Service with @Injectable
Open my-service.service.ts. You'll see the @Injectable decorator applied to the MyService class. The providedIn property specifies where Angular should provide this service. In this case, it is set to 'root', which means the service is available application-wide.
Here’s an example of how you might define a service:
JavaScript
//my-service.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor() { }
getValue(): string {
return 'Hello from MyService!';
}
}
- providedIn root: This tells Angular to provide the service in the root injector, making it a singleton and available throughout the application.
- constructor: The constructor can be used to inject other services or dependencies.
Step 4: Inject the Service into a Component
Next, let’s use the MyService in a component. Open or create a component, for example, app.component.ts.
JavaScript
//app.component.ts
import { Component } from '@angular/core';
import { MyService } from './my-service.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
standalone: true
})
export class AppComponent {
value: string;
// Inject the service into the component
constructor(private myService: MyService) {
// Use the service
this.value = this.myService.getValue();
}
}
In this example, the MyService is injected into the AppComponent through the constructor. You can then use it as needed within the component.
Step 5: Update Component Template
You can display the value retrieved from the service in the component's template.
HTML
<!--app.component.html-->
<h1>{{ value }}</h1>
Step 6: Ensure Dependency Injection is Working
Run your Angular application to verify that the service is being used correctly.
ng serve
Navigate to http://localhost:4200 in your browser. You should see "Hello from MyService!" rendered on the page.
How To Use @Injectable Decorator In Angular
Similar Reads
How To Use Reactive Forms in Angular?
In Angular, the forms are an important part of handling user input and validation. Reactive Forms offers a model-driven approach that provides greater control and flexibility by managing form controls, validation, and data binding directly within the component class. Core ComponentsFormGroup: Repres
5 min read
Purpose of NgModule Decorator in Angular
The NgModule decorator in Angular is like a blueprint for organizing and configuring different parts of your application. It's like a set of instructions that tells Angular how to assemble the various components, directives, pipes, and services into cohesive units called modules. These modules help
5 min read
How to use Mat-Dialog in Angular ?
Introduction:Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can downloa
3 min read
How to Use the Async Pipe in Angular?
The AsyncPipe in Angular is a powerful and convenient tool used to handle asynchronous data streams such as observables and promises directly in the component template. It automatically subscribes to observables, renders their values, and updates the view when new data is emitted. This removes the n
3 min read
Input Decorator In Angular
The @Input decorator in Angular is used to pass data from the parent to child components. It allows a parent component to bind data to properties in a child component enabling the sharing of data between components in a hierarchical relationship. The @Input decorator is important for communication b
4 min read
How To Use OnChanges In Angular?
Angular is a powerful framework for building dynamic web applications, and one of its core features is the ability to manage and react to changes in component data. One of the key lifecycle hooks in Angular for responding to changes in input properties is the OnChanges lifecycle hook. This hook is h
3 min read
Creating an injectable service in Angular
In Angular, services are a great way to share data, functionality, and state across different components in your application. Services are typically injected into components and other services as dependencies, making them easily accessible and maintainable. Mostly services are used to create functio
3 min read
How to create class in Angular Project?
In Angular, TypeScript is the primary language for writing code. One of the fundamental concepts in TypeScript is classes, which allow you to define blueprints for creating objects with properties and methods. In this article, we'll explore how to create classes in Angular projects and understand th
2 min read
HTTP Interceptor use-cases in Angular
In Angular, HTTP interceptors are a powerful feature that allows you to intercept and modify HTTP requests and responses at a centralized location. They act as middleware, sitting between the applicationâs HTTP client (typically the built-in HttpClient module) and the server.In this article, we will
6 min read
How to inject service in angular 6 component ?
Service is a special class in Angular that is primarily used for inter-component communication. It is a class having a narrow & well-defined purpose that should perform a specific task. The function, any value, or any feature which may application required, are encompassed by the Service. In oth
4 min read