Lesson 12 / 30
Creating a Service
Pull shared logic and state out of components.
@Injectable
A service is a plain class marked @Injectable that holds logic or state you don't want duplicated in every component.
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class CartService {
private items: string[] = [];
add(item: string) {
this.items.push(item);
}
getItems() {
return this.items;
}
}providedIn: 'root'
providedIn: 'root' registers the service as a single app-wide singleton — the same instance is shared everywhere it's injected.