0
0
Angularframework~5 mins

Why services are needed in Angular

Choose your learning style9 modes available
Introduction

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.

When multiple components need to use the same data or functions.
When you want to keep your components simple and focused on the user interface.
When you need to get data from a server and share it with many parts of your app.
When you want to handle tasks like logging or user authentication in one place.
When you want to make your app easier to test by separating logic from UI.
Syntax
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.

Examples
A simple service that provides a list of fruits.
Angular
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class DataService {
  getData() {
    return ['apple', 'banana', 'cherry'];
  }
}
A service to handle logging messages from anywhere in the app.
Angular
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class LoggerService {
  log(message: string) {
    console.log('LOG:', message);
  }
}
Sample Program

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.

Angular
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();
  }
}
OutputSuccess
Important Notes

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.

Summary

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.