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.
A Service is a class responsible for:
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}1ng generate service services/katana
2# or shorter:
3ng g s services/katana