Creating an injectable service in Angular
Last Updated :
22 Mar, 2024
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:
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",
"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
//app.component.ts
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { MyService } from './core/services/my-service.service';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, CommonModule],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
title = 'injectible-service-demo';
items: any[] = [];
constructor(private myService: MyService) {
this.items = this.myService.getData();
}
addItem() {
const newItem = { id: Date.now(), value: 'New Item' };
this.myService.addData(newItem);
this.items = this.myService.getData();
}
}
JavaScript
//my-service.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyService {
private data: any[] = [];
getData() {
return this.data;
}
addData(item: any) {
this.data.push(item);
}
}
Output:
Creating an injectable service - Angular
Similar Reads
Creating An Interface In Angular
In Angular, an interface is a TypeScript feature that defines the shape or structure of an object. It helps developers enforce type safety by specifying what properties and types an object must have. Interfaces do not generate JavaScript code but are used during the development phase to ensure that
4 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
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
Explain the steps for creating a services in Angular 2
If you've ever constructed a component, you're aware that the component contains an executable code, allowing you to include any functionality that you want. The task of the component is to enable the user experience, which will interact with the user. The component will act as an intermediate betwe
6 min read
AngularJS $exceptionHandler Service
In AngularJS, a service is a function or object that is available for dependency injection (DI) in an AngularJS app. Services are typically used to encapsulate and reuse business logic and other app functionality that is not directly related to the presentation of data in the app. The $exceptionHand
4 min read
AngularJS $interval Service
The $interval service in AngularJS is a function that allows you to execute a function repeatedly at a specified interval. It is similar to the setInterval function in JavaScript, but it is designed to work seamlessly with the AngularJS framework. To use the $interval service, it is first needed to
4 min read
AngularJS $locale service
The AngularJS $locale service is a built-in service that provides localization information for the current browser environment. It is designed to help developers create applications that can be easily adapted to different locales and languages. The $locale service exposes a number of properties that
4 min read
Explain the role of the root injector in Angular.
Angular's dependency injection enables modular and reusable components across applications. At the core of dependency injection lies the root injector, a powerful mechanism responsible for managing dependencies and providing instances of services, components, directives, and more throughout the appl
4 min read
AngularJS $controller Service
AngularJS applications depend on a controller to control the flow of data through an AngularJS application. AngularJS architecture uses the MVC model i.e the Model View Controller. The model is responsible for maintaining the application data, the View for displaying data or some part of data to the
5 min read
Angular 7 | Angular Data Services using Observable
Observables Observable manage async data and a few other useful patterns. Observables are similar to Promises but with a few key differences. Unlike Promises, Observables emit multiple values over time. In real scenarios, web socket or real-time based data or event handlers can emit multiple values
4 min read