一个服务是一个类,用于非 UI 逻辑 — 数据获取、业务规则、共享状态、日志 — 组件可以重新使用。**依赖注入(DI)**是 Angular 向需要这些服务的组件提供这些服务的方式,而不是让组件手动创建它们。
定义服务
ts
{ } ;
({ : })
{
users = [];
() { .; }
() { ..(u); }
}
一个服务是一个类,用于非 UI 逻辑 — 数据获取、业务规则、共享状态、日志 — 组件可以重新使用。**依赖注入(DI)**是 Angular 向需要这些服务的组件提供这些服务的方式,而不是让组件手动创建它们。
{ } ;
({ : })
{
users = [];
() { .; }
() { ..(u); }
}
@Injectable({ providedIn: "root" }) 装饰器将服务注册到 Angular 的 DI 系统,作为整个应用的单个共享实例(单例)。
@Component({ ... })
export class UserListComponent {
// Angular sees this constructor param and INJECTS the singleton automatically
constructor(private userService: UserService) {}
users = this.userService.getUsers(); // just use it
}
你只需将服务声明为构造函数参数;Angular 的 DI 创建并供应实例。你永远不需要写 new UserService()。(现代 Angular 也可以使用 inject() 函数而不是构造函数注入。)
import { inject } from "@angular/core";
export class UserListComponent {
private userService = inject(UserService); // alternative injection style
}
✓ Single source of truth — one shared UserService instance across components
✓ Loose coupling — components depend on the type, not on constructing it
✓ Testability — swap in a mock service in tests easily
✓ Lifecycle management — Angular handles creation and sharing
因为组件不构造其依赖项,你可以在测试中注入一个假服务,或在一处改变整个应用的实现。
服务 + DI 是 Angular 架构的核心:组件专注于 UI,而服务保存逻辑和状态,DI 以最小耦合将它们连接在一起。
这种分离(以及它带来的可测试性)是 Angular 的定义优势之一 — 从后端框架借鉴而来 — 而 @Injectable({ providedIn: 'root' }) 是用于共享、可注入单例的日常模式。