Open In App

Creating an injectable service in Angular

Last Updated : 22 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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 functions that initiate HTTP calls.

What is an Injectable Service?

An injectable service in Angular is a TypeScript class decorated with the @Injectable() decorator. This decorator provides metadata that allows Angular's dependency injection system to create and manage instances of the service class. Injectable services play a fundamental role in Angular development as they provide a way to share functionality, data, and state across different parts of the application.

Syntax:

import { Injectable } from '@angular/core';

@Injectable({
providedIn: 'root' // or 'any' or specific module
})
export class MyService {
constructor() { }

// Service logic here
}

Steps to Create An Injectable Service:

Step 1: Setting Up Angular Project

Install Angular CLI globally (if not already installed)

npm install -g @angular/cli

Step 2: Create a new Angular project:

ng new injectible-service-demo

Step 3: Once the project is set up, navigate to the src/app directory. Inside it, create a new folder called "core". Within the "core" folder, create another folder named "services".

Step 4: Generate a new service using the angular cli after going into services folder using the below command:

ng generate service my-service

Folder Structure:

wergf
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"
},
"devDependencies": {
"@angular-devkit/build-angular": "^17.3.0",
"@angular/cli": "^17.3.0",
"@angular/compiler-cli": "^17.3.0",
"@types/jasmine": "~5.1.0",
"jasmine-core": "~5.1.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"typescript": "~5.4.2"
}

Example of Injectable Services in Angular

Code: Add the following codes in respective files.

HTML
<!-- app.component.html -->

<div>
    <button (click)="addItem()">Add Item</button>
    <ul>
        <li *ngFor="let item of items">{{ item | json }}</li>
    </ul>
</div>
JavaScript JavaScript

Output:


Animation48
Creating an injectable service - Angular



Next Article

Similar Reads

three90RightbarBannerImg