关于 angular-di
面向 Angular 21 依赖注入配置的开发者参考技能,介绍 inject()、提供者、令牌和注入器作用域,并给出常见依赖模式示例。
主要功能
- 01使用 inject() 进行函数式注入
- 02服务与 InjectionToken 提供者
- 03工厂提供者与多提供者
- 04可选依赖与 SkipSelf
- 05分层注入器作用域
适用场景
- 01在组件中注入服务
- 02提供非类配置值
- 03配置多个实现
- 04将服务限定到组件或模块
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ oguzhan18/ angular-ecosystem-skills --skill angular-di安装后在 Claude Code 中输入/angular-di确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/discussions/_INDEX.mdreferences/docs/_INDEX.mdreferences/issues/_INDEX.mdreferences/releases/_INDEX.md详细介绍
Angular 依赖注入
版本: Angular 21(2025 年) 标签: DI、服务、提供者、令牌、inject()
API 变更
本节介绍近期特定版本的 API 变更。
-
新增:使用 inject() 进行函数式注入 — 在现代 Angular 中,优先于构造函数注入 来源
-
新增:inject() 搭配 Optional 装饰器 —
inject(Service, { optional: true }) -
新增:inject() 搭配 SkipSelf —
inject(Service, { skipSelf: true }) -
新增:支持摇树优化的 InjectionToken —
new InjectionToken<T>(desc, { providedIn: 'root' })
最佳实践
- 单例服务使用 providedIn: 'root'
@Injectable({ providedIn: 'root' })
export class LoggerService {
log(message: string) { console.log(message); }
}
- 使用 inject() 函数,让代码更简洁
@Component({})
export class MyComponent {
private service = inject(MyService);
private router = inject(Router);
}
- 非类依赖项使用 InjectionToken
export const API_URL = new InjectionToken<string>('apiUrl');
providers: [
{ provide: API_URL, useValue: 'https://api.example.com' }
]
constructor(@Inject(API_URL) private apiUrl: string) {}
- 复杂实例化使用工厂提供者
providers: [
{
provide: AuthService,
useFactory: (http: HttpClient, config: AppConfig) => {
return new AuthService(http, config.apiUrl);
},
deps: [HttpClient, APP_CONFIG]
}
]
- 多个实现使用多提供者
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: LogInterceptor, multi: true }
]
- 可选依赖项使用 @Optional
constructor(@Optional() private logger: LoggerService) {
this.logger?.log('Optional dependency');
}
- 使用 @SkipSelf 避免注入自身
constructor(@SkipSelf() @Optional() private parent: ParentService) {}
- 循环依赖使用 forwardRef
constructor(@Inject(forwardRef(() => ParentService)) private parent: ParentService) {}
- 使用层级注入器进行作用域管理
// Component-level provider
@Component({
providers: [MyService]
})
export class MyComponent {}
// Lazy-loaded module provider
@Injectable({ providedIn: MyModule })
export class MyService {}
- 使用接口注入模式
export interface CacheInterface {
get(key: string): any;
}
export const CACHE_TOKEN = new InjectionToken<CacheInterface>('cache');
- 延迟加载的服务使用 providedIn: 'any'
@Injectable({ providedIn: 'any' })
export class LazyService {}
评论
支持 Markdown