Community코딩 & 개발github.com

analogjs/angular-di

Angular v20+에서 inject(), injection tokens, provider 구성을 사용한 의존성 주입 구현. 서비스 아키텍처, 다양한 수준에서의 의존성 제공, 인젝터블 토큰 생성, 싱글톤 및 범위 서비스 관리에 사용됩니다.

angular-di란 무엇인가요?

이 스킬은 Angular v20+ 애플리케이션에서 의존성 주입(Dependency Injection)을 구현하는 방법을 제공합니다. 개발자는 `inject()` 함수, 인젝션 토큰(Injection Tokens), 프로바이더(Provider) 구성을 사용하여 서비스 아키텍처를 구축하고 의존성을 다양한 수준(컴포넌트, 모듈, 애플리케이션 루트)에서 제공할 수 있습니다. 또한 인젝터블 토큰을 생성하여 타입 안전성을 확보하고, `providedIn` 또는 프로바이더 배열을 통해 싱글톤과 범위 서비스의 생명주기를 관리할 수 있습니다. 이 스킬은 서비스 생성, 프로바이더 구성, 인젝션 토큰 사용, DI 계층 구조 이해와 같은 작업에서 활성화됩니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/analogjs/angular-skills/tree/main/skills/angular-di

Installed? Explore more 코딩 & 개발 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

angular-di은(는) 무엇을 하나요?

Angular v20+에서 inject(), 인젝션 토큰(Injection Tokens), 프로바이더(Provider) 구성을 사용한 의존성 주입(Dependency Injection)을 구현합니다. 서비스 아키텍처, 다양한 수준에서의 의존성 제공, 인젝터블 토큰 생성, 싱글톤 및 범위 서비스 관리에 사용됩니다. 서비스 생성, 프로바이더 구성, 인젝션 토큰 사용, DI 계층 구조 이해 시 트리거됩니다.

개요

Angular의 의존성 주입 시스템은 애플리케이션 전반에 걸쳐 의존성을 관리하는 강력한 방법입니다. 이 스킬은 최신 Angular v20+ 기능을 활용하여 효율적이고 유지보수 가능한 서비스 아키텍처를 구축하는 방법을 안내합니다.

주요 기능

  • inject() 함수: 생성자 기반 주입 대신 함수 내에서 직접 의존성을 주입할 수 있습니다.
  • 인젝션 토큰: 타입 안전한 토큰을 생성하여 서비스나 값을 식별하고 주입합니다.
  • 프로바이더 구성: 다양한 수준(루트, 모듈, 컴포넌트)에서 프로바이더를 구성합니다.
  • 싱글톤 및 범위 서비스: providedIn 속성이나 프로바이더 배열을 사용하여 서비스의 생명주기를 제어합니다.

사용 방법

1. 기본 서비스 생성

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root', // 애플리케이션 전체에서 싱글톤
})
export class DataService {
  private data: string[] = [];

  getData(): string[] {
    return this.data;
  }

  addData(item: string): void {
    this.data.push(item);
  }
}

2. 인젝션 토큰 사용

import { InjectionToken } from '@angular/core';

export const API_URL = new InjectionToken<string>('API_URL');
// 프로바이더 구성
providers: [
  { provide: API_URL, useValue: 'https://api.example.com' }
]

3. inject() 함수로 주입

import { inject } from '@angular/core';

export class UserService {
  private dataService = inject(DataService);
  private apiUrl = inject(API_URL);

  getUsers() {
    return this.dataService.getData();
  }
}

4. 다양한 수준의 프로바이더

컴포넌트 수준에서 프로바이더를 재정의하여 범위 제한:

@Component({
  selector: 'app-user-list',
  template: `...`,
  providers: [
    { provide: DataService, useClass: MockDataService }
  ]
})
export class UserListComponent {
  private dataService = inject(DataService);
}

DI 계층 구조

Angular의 의존성 주입은 계층적 구조를 따릅니다:

  1. 루트 인젝터: providedIn: 'root'로 등록된 서비스는 앱 전체에서 공유됩니다.
  2. 모듈 인젝터: @NgModule({ providers: [...] })로 등록된 서비스는 해당 모듈 범위 내에서 공유됩니다.
  3. 컴포넌트 인젝터: @Component({ providers: [...] })로 등록된 서비스는 해당 컴포넌트와 자식 컴포넌트에서만 유효합니다.

의존성 조회는 현재 컴포넌트에서 시작하여 상위 인젝터로 전파되며, 루트 인젝터까지 찾지 못하면 오류가 발생합니다.

팁

  • inject() 함수는 생성자보다 유연하며, 가드나 인터셉터 같은 함수형 코드에서도 사용할 수 있습니다.
  • 인젝션 토큰을 사용하면 타입 안전성을 유지하면서 값이나 서비스를 주입할 수 있습니다.
  • 범용 서비스는 providedIn: 'root'로 설정하고, 특정 상황에서만 필요한 서비스는 컴포넌트 수준에서 제공하세요.

참고

Individual skills in this repo

This repo contains 9 individual skills — each has its own dedicated page.

analogjs/angular-component

Create modern Angular standalone components following v20+ best practices. Use for building UI components with signal-based inputs/outputs, OnPush change detection, host bindings, content projection, and lifecycle hooks. Triggers on component creation, refactoring class-based inputs to signals, adding host bindings, or implementing accessible interactive components.

analogjs/angular-directives

Create custom directives in Angular v20+ for DOM manipulation and behavior extension. Use for attribute directives that modify element behavior/appearance, structural directives for portals/overlays, and host directives for composition. Triggers on creating reusable DOM behaviors, extending element functionality, or composing behaviors across components. Note - use native @if/@for/@switch for control flow, not custom structural directives.

analogjs/angular-forms

Build signal-based forms in Angular v21+ using the new Signal Forms API. Use for form creation with automatic two-way binding, schema-based validation, field state management, and dynamic forms. Triggers on form implementation, adding validation, creating multi-step forms, or building forms with conditional fields. Signal Forms are experimental but recommended for new Angular projects. Don't use for template-driven forms without signals or third-party form libraries like Formly or ngx-formly.

analogjs/angular-http

Implement HTTP data fetching in Angular v20+ using resource(), httpResource(), and HttpClient. Use for API calls, data loading with signals, request/response handling, and interceptors. Triggers on data fetching, API integration, loading states, error handling, or converting Observable-based HTTP to signal-based patterns.

analogjs/angular-routing

Implement routing in Angular v20+ applications with lazy loading, functional guards, resolvers, and route parameters. Use for navigation setup, protected routes, route-based data loading, and nested routing. Triggers on route configuration, adding authentication guards, implementing lazy loading, or reading route parameters with signals.

analogjs/angular-signals

Implement signal-based reactive state management in Angular v20+. Use for creating reactive state with signal(), derived state with computed(), dependent state with linkedSignal(), and side effects with effect(). Triggers on state management questions, converting from BehaviorSubject/Observable patterns to signals, or implementing reactive data flows.

analogjs/angular-ssr

Implement server-side rendering and hydration in Angular v20+ using @angular/ssr. Use for SSR setup, hydration strategies, prerendering static pages, and handling browser-only APIs. Triggers on SSR configuration, fixing hydration mismatches, prerendering routes, or making code SSR-compatible.

analogjs/angular-testing

Write unit and integration tests for Angular v20+ applications using Vitest or Jasmine with TestBed and modern testing patterns. Use for testing components with signals, OnPush change detection, services with inject(), and HTTP interactions. Triggers on test creation, testing signal-based components, mocking dependencies, or setting up test infrastructure. Don't use for E2E testing with Cypress or Playwright, or for testing non-Angular JavaScript/TypeScript code.

analogjs/angular-tooling

Use Angular CLI and development tools effectively in Angular v20+ projects. Use for project setup, code generation, building, testing, and configuration. Triggers on creating new projects, generating components/services/modules, configuring builds, running tests, or optimizing production builds. Don't use for Nx workspace commands, custom Webpack configurations, or non-Angular CLI build systems like Vite standalone or esbuild direct usage.

관련 스킬