Introduction to Services
Imagine you run a large restaurant. Every waiter needs to know the menu, prices, and daily specials. Instead of giving each waiter their own menu book that you have to update individually, you have one central menu that everyone uses. If prices change, you update one place and all waiters see the new prices. Services in Angular work exactly like that central menu.
A service is a class with a specific purpose – often to share data, logic, or functionality across multiple components. Services help you:
- Avoid code duplication – Write once, use everywhere.
- Share data between unrelated components.
- Separate concerns – Keep components focused on the UI, services focused on logic/data.
- Make testing easier – Services can be tested independently.
Here's a simple service that provides user data:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class UserService {
private users = [
{ id: 1, name: 'John', email: 'john@example.com' },
{ id: 2, name: 'Jane', email: 'jane@example.com' }
];
getUsers() {
return this.users;
}
getUserById(id: number) {
return this.users.find(user => user.id === id);
}
}
Services are just regular TypeScript classes with the
@Injectable decorator. This decorator tells Angular that this class can be injected into other classes.Two Minute Drill
- Services are classes that provide reusable logic or data.
- Use @Injectable decorator to make a class injectable.
- Services help share data between components.
- They keep components lean by moving logic out.
- Services can be tested independently.
Need more clarification?
Drop us an email at career@quipoinfotech.com
