We use cookies to enhance your experience on the site
CodeWorlds

Services in Angular - Craftsmen Guilds

Services in Angular are like craftsmen guilds - specialized units providing services to the entire kingdom. Each guild has its specialization: blacksmiths forge swords, tailors sew kimonos.

What is a Service?

A Service is a class responsible for:

  • Business logic - calculations, validations
  • API communication - fetching/sending data
  • State management - storing data between components
  • Code sharing - avoiding duplication

Creating a Service

1import { Injectable } from '@angular/core';
2
3@Injectable({
4  providedIn: 'root'  // Singleton available throughout the application
5})
6export class KatanaService {
7  private katanas: Katana[] = [];
8
9  getAll(): Katana[] {
10    return [...this.katanas]; // We return a copy
11  }
12
13  getById(id: number): Katana | undefined {
14    return this.katanas.find(k => k.id === id);
15  }
16
17  forge(name: string, type: string): Katana {
18    const katana: Katana = {
19      id: Date.now(),
20      name,
21      type,
22      damage: Math.floor(Math.random() * 100) + 50,
23      createdAt: new Date()
24    };
25    this.katanas.push(katana);
26    return katana;
27  }
28
29  destroy(id: number): boolean {
30    const index = this.katanas.findIndex(k => k.id === id);
31    if (index > -1) {
32      this.katanas.splice(index, 1);
33      return true;
34    }
35    return false;
36  }
37}

Generating via CLI

1ng generate service services/katana
2# or shorter:
3ng g s services/katana
Go to CodeWorlds