大型 Angular 应用中,一个组件可能依赖 API、权限、配置和日志服务。如果组件直接创建这些对象,测试和环境切换会变得困难。Angular 依赖注入让实例创建与使用分离。本文围绕工作台通知服务介绍提供者、注入令牌及实例生命周期。
1. 把业务依赖与展示分离
通知组件只需要读取记录和发送已读操作,不需要知道具体是 HTTP 接口还是测试数据源。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/f7fb53f771a9cd0b32c7b7206177a5f51ac94d67">
<section><h2>通知中心</h2><p>显示工作区消息</p></section>
</div>
export interface NoticeRepository {
list(): Promise<Notice[]>;
markRead(id: string): Promise<void>;
}
2. 为接口创建运行时令牌
TypeScript interface 会在编译后消失,不能直接充当 Angular 注入键。使用 InjectionToken 为接口建立运行时身份。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/ff03ff0cbae91e018fc6cb04c5e41e7c80a1b835">
<p role="status">{
{ status }}</p>
</div>
import {
InjectionToken } from '@angular/core';
export const NOTICE_REPOSITORY = new InjectionToken<NoticeRepository>('NoticeRepository');
3. 通过 useClass 配置实现
提供者可以把令牌映射到具体实现。组件依赖抽象契约,实际实例由注入器管理。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/4f9a787a218b40a582497a6234eb752663a6306b">
<ul>@for (notice of notices; track notice.id) { <li>{
{ notice.title }}</li> }</ul>
</div>
@Injectable()
export class HttpNoticeRepository implements NoticeRepository {
// 在此实现 list 和 markRead,封装 HTTP 调用。
}
// 应用 providers 中配置:
{
provide: NOTICE_REPOSITORY, useClass: HttpNoticeRepository }
4. 在组件中使用 inject
inject 可以在 Angular 创建对象时的注入上下文中使用,例如字段初始化器。它不能任意放在之后触发的普通回调中调用。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/4759071e38859cf641eaf059b4a791d334cc119c">
<button type="button" (click)="refresh()">刷新通知</button>
</div>
private readonly repository = inject(NOTICE_REPOSITORY);
async refresh() {
this.notices = await this.repository.list(); }
5. 选择应用级或组件级作用域
应用级服务适合共享会话和通用能力。组件级 providers 可以为每个独立编辑面板创建单独实例,并随该组件的生命周期结束。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/76418c12ac0758d3987580462ce057d664688372">
<section><app-notice-panel /><app-notice-panel /></section>
</div>
@Component({
selector: 'app-notice-panel', providers: [NoticeSelectionService], templateUrl: './notice-panel.html' })
export class NoticePanelComponent {
}
6. 通过 useValue 注入只读配置
接口地址或功能策略可以作为明确的配置对象提供,不必在每个组件内部重复写字符串。注入并不会自动使对象不可变。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/097eae212646aab4eb3f7216f9e635b589692066">
<p>当前通知刷新策略:{
{ config.refreshLabel }}</p>
</div>
export const NOTICE_CONFIG = new InjectionToken<Readonly<NoticeConfig>>('NoticeConfig');
const provider = {
provide: NOTICE_CONFIG, useValue: Object.freeze(environment.noticeConfig) };
7. 利用 useFactory 组合依赖
工厂提供者适合根据注入的配置创建实例。保持工厂简单,不要把昂贵初始化或不可控网络写入藏在实例构造阶段。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/d20a4ef58f781077cdf42606deadb704e041699e">
<section><h3>消息来源</h3><p>{
{ sourceLabel }}</p></section>
</div>
const provider = {
provide: NOTICE_REPOSITORY,
useFactory: () => createNoticeRepository(inject(NOTICE_CONFIG), inject(HttpClient))
};
8. 使用 useExisting 避免重复实例
如果两个令牌表示同一服务实例,可以使用 useExisting 建立别名。useClass 则可能创建另一个实例,从而导致状态重复。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/c67ad9feb927a1c3c728a53bd04418c3bf624e63">
<output>{
{ unreadCount }}</output>
</div>
const providers = [HttpNoticeRepository, {
provide: NOTICE_REPOSITORY, useExisting: HttpNoticeRepository }];
9. 管理服务内部订阅生命周期
组件作用域服务可能拥有 Observable 订阅或外部事件。可以利用 DestroyRef 或 takeUntilDestroyed,使资源随对应注入上下文清理。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/b79a134c126e9bd7f27da79f2a33bbad350b7ef1">
<p aria-live="polite">{
{ connectionStatus }}</p>
</div>
private readonly destroyRef = inject(DestroyRef);
connect() {
this.events.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(event => this.apply(event));
}
10. 利用替代提供者测试业务
测试不需要启动真实网络服务。将接口令牌替换为 fake 实现,验证组件如何处理正常结果、空数据和失败。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/fe110286a84374724bf24554b23aef731c10a2c7">
<section><p>{
{ notices.length }} 条通知</p></section>
</div>
TestBed.configureTestingModule({
providers: [{
provide: NOTICE_REPOSITORY, useValue: fakeRepository }] });
expect(TestBed.inject(NOTICE_REPOSITORY)).toBe(fakeRepository);
总结
依赖注入的主要价值是明确实例所有权和可替换边界。使用类型化令牌、合理的提供者作用域及生命周期清理,可以让 Angular 服务在复杂项目中保持一致且便于测试。
推荐阅读
SvelteKit load 实战:服务端数据读取、页面依赖与失效更新
https://github.com/tiktokwuyu-ux/technical-notes/commit/cc161de407f18c17088cb3532b8784fb6cbe3fe9
Vite 工程化实战:环境变量、动态模块加载与多环境构建
https://github.com/tiktokwuyu-ux/technical-notes/commit/b79a134c126e9bd7f27da79f2a33bbad350b7ef1
JavaScript History API 实战:单页导航、前进后退与滚动恢复
https://github.com/tiktokwuyu-ux/technical-notes/commit/4759071e38859cf641eaf059b4a791d334cc119c
Svelte 动画实战:transition、animate 与列表重排交互
https://github.com/tiktokwuyu-ux/technical-notes/commit/c67ad9feb927a1c3c728a53bd04418c3bf624e63
Vue 3 插槽实战:作用域插槽、可复用表格与组件 API 设计
https://github.com/tiktokwuyu-ux/technical-notes/commit/f7fb53f771a9cd0b32c7b7206177a5f51ac94d67
Nuxt useAsyncData 实战:服务端数据预取、请求去重与刷新控制
https://github.com/tiktokwuyu-ux/technical-notes/commit/c0ec79cfc95bc481145d72a4e705799aa2e7cbcf
React useId 与无障碍组件实战:表单关联、提示信息与组件复用
https://github.com/tiktokwuyu-ux/technical-notes/commit/d20a4ef58f781077cdf42606deadb704e041699e
JavaScript 事件循环实战:微任务、渲染时机与长任务拆分
https://github.com/tiktokwuyu-ux/technical-notes/commit/cedc8253b2750a0b31800e5be4d570c6ac666958
React useReducer 实战:复杂组件状态转换与可测试的业务流程
https://github.com/tiktokwuyu-ux/technical-notes/commit/9230820adc2173383c177b3abd09fd51a5c65e47
Vue Router 4 实战:导航守卫、权限路由与离开页面确认
https://github.com/tiktokwuyu-ux/technical-notes/commit/893c790be6c761f08885628d340c77d3517298d1