Open In App

How To Use @Injectable Decorator In Angular?

Last Updated : 24 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  1. my-service.service.ts
  2. my-service.service.spec.ts (for testing)

Folder Structure

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",
"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.

file
How To Use @Injectable Decorator In Angular

Next Article

Similar Reads