Roadmap › Angular (2 → 21) › Module: Services, DI and HTTP
Lessons in this course (16)
6. Services and dependency injection
Intermediate★ Must knowLesson 6 of 16
ts
@Injectable({ providedIn: "root" }) // app-wide singleton, tree-shakable
export class OrderService {
private http = inject(HttpClient); // inject() function (or constructor injection)
list() { return this.http.get<Order[]>("/api/orders"); }
}
// Component-level provider: a new instance per component instance
@Component({ selector: "app-wizard", providers: [WizardState], template: "" })
export class Wizard { state = inject(WizardState); }
// Injection tokens for non-class values
export const API_URL = new InjectionToken<string>("API_URL");
// app.config.ts: providers: [{ provide: API_URL, useValue: "https://api.example.com" }]Provider recipes: useClass, useValue, useFactory, useExisting. Hierarchical injectors: environment (root/platform/route) injectors and element (component) injectors — Angular looks up from the component to its ancestors to the root. Resolution modifiers: { optional: true }, { self: true }, { skipSelf: true }, { host: true }.