What is a service in Angular and when would you use one?

Beginner

Answer

A service is a class with a specific purpose that provides functionality not directly related to views. Services are used for:

  • Data sharing between components
  • Business logic that shouldn't be in components
  • External communication (HTTP requests)
  • Utility functions and helpers
  • State management

Creating a service:

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

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private data: string[] = [];

  getData(): string[] {
    return this.data;
  }

  addData(item: string): void {
    this.data.push(item);
  }
}