Services help share data and logic across different parts of an Angular app. They keep code organized and avoid repeating the same work in many places.
Why services are needed in Angular
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class MyService { // service logic here }
The @Injectable decorator marks the class as a service that can be injected.
Using providedIn: 'root' makes the service available app-wide without extra setup.
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataService { getData() { return ['apple', 'banana', 'cherry']; } }
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class LoggerService { log(message: string) { console.log('LOG:', message); } }
This example shows a service that stores messages. The component uses the service to add and display messages. This keeps the message logic separate from the UI.
import { Component } from '@angular/core'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class MessageService { private messages: string[] = []; add(message: string) { this.messages.push(message); } getMessages() { return this.messages; } } @Component({ selector: 'app-root', template: ` <h1>Messages</h1> <button (click)="addMessage()">Add Message</button> <ul> <li *ngFor="let msg of messages">{{ msg }}</li> </ul> ` }) export class AppComponent { messages: string[] = []; count = 1; constructor(private messageService: MessageService) { this.messages = this.messageService.getMessages(); } addMessage() { this.messageService.add(`Message ${this.count++}`); this.messages = this.messageService.getMessages(); } }
Services help keep your app clean by separating data and logic from the user interface.
Injecting services makes it easy to reuse code and share information between components.
Always use services for tasks like data fetching, state management, or utility functions.
Services let you share data and logic across your Angular app.
They keep components simple and focused on displaying the UI.
Using services makes your app easier to maintain and test.