Example of Injectable Services in Angular
Code: Add the following codes in respective files.
<!-- app.component.html -->
<div>
<button (click)="addItem()">Add Item</button>
<ul>
<li *ngFor="let item of items">{{ item | json }}</li>
</ul>
</div>
//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();
}
}
//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 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 functions that initiate HTTP calls.
Table of Content
- What is an Injectable Service?
- Steps to Create An Injectable Service
- Example of Injectable Services in Angular