Logo Angular Dependency Injection

Angular Dependency Injection

Tổ chức
TheBushidoCollective
angular-dependency-injection

Use when building modular Angular applications requiring dependency injection with providers, injectors, and services.

Tổng quan

Nhà phát hànhTheBushidoCollective
Kho mãhan
Tên kỹ năngangular-dependency-injection
Sao
195
Bản fork
20
Tệp đi kèm
Chỉ có hướng dẫn
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI là Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • Đầy đủ trong hướng dẫn

    Mọi thứ mô hình cần đều nằm trong hướng dẫn — không có tệp bổ sung cần đồng bộ.

  • Mã nguồn mở

    Được TheBushidoCollective công bố trên GitHub. Hãy đọc nội dung nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Angular Dependency Injection trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL thư mục kỹ năng bên dưới và xác nhận.
    https://github.com/TheBushidoCollective/han/tree/main/plugins/frameworks/angular/skills/angular-dependency-injection
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/TheBushidoCollective/han.git /tmp/han
mkdir -p .claude/skills
cp -r /tmp/han/plugins/frameworks/angular/skills/angular-dependency-injection .claude/skills/angular-dependency-injection
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Angular Dependency Injection trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự tải Angular Dependency Injection ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên Angular Dependency Injection không bị giới hạn ở mô hình mà kỹ năng này được viết cho. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên kỹ năng chưa dùng không tốn chi phí.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

Angular Dependency Injection

Master Angular's dependency injection system for building modular, testable applications with proper service architecture.

DI Fundamentals

Angular's DI uses the inject() function (Angular 14+) as the preferred injection mechanism — no constructor parameters needed:

typescript
import { Injectable, inject } from '@angular/core';

// Service injectable at root level
@Injectable({
  providedIn: 'root'
})
export class UserService {
  private users: User[] = [];

  getUsers(): User[] {
    return this.users;
  }

  addUser(user: User): void {
    this.users.push(user);
  }
}

// Standalone component injection via inject()
import { Component } from '@angular/core';

@Component({
  selector: 'app-user-list',
  standalone: true,
  template: `
    @for (user of users; track user.id) {
      <div>{{ user.name }}</div>
    }
  `
})
export class UserListComponent {
  private readonly userService = inject(UserService);
  users = this.userService.getUsers();
}

Provider Types

useClass - Class Provider

typescript
import { Injectable, Provider, Component, inject } from '@angular/core';

// Interface
interface Logger {
  log(message: string): void;
}

// Implementations
@Injectable()
export class ConsoleLogger implements Logger {
  log(message: string): void {
    console.log(message);
  }
}

@Injectable()
export class FileLogger implements Logger {
  log(message: string): void {
    // Write to file
  }
}

// Provider configuration
const loggerProvider: Provider = {
  provide: Logger,
  useClass: ConsoleLogger
};

// Standalone component — providers go here, not in NgModule
@Component({
  selector: 'app-my-component',
  standalone: true,
  providers: [loggerProvider],
  template: `...`
})
export class MyComponent {
  private readonly logger = inject(Logger);

  constructor() {
    this.logger.log('Component initialized');
  }
}

useValue - Value Provider

typescript
import { InjectionToken, Component, inject } from '@angular/core';

// Configuration object
export interface AppConfig {
  apiUrl: string;
  timeout: number;
  retries: number;
}

export const APP_CONFIG = new InjectionToken<AppConfig>('app.config');

// Provider
const configProvider = {
  provide: APP_CONFIG,
  useValue: {
    apiUrl: 'https://api.example.com',
    timeout: 5000,
    retries: 3
  }
};

// bootstrapApplication (standalone)
bootstrapApplication(AppComponent, {
  providers: [configProvider]
});

// Usage via inject()
export class ApiService {
  private readonly config = inject(APP_CONFIG);

  constructor() {
    console.log(this.config.apiUrl);
  }
}

useFactory - Factory Provider

typescript
import { Injectable, InjectionToken, inject } from '@angular/core';

export const API_URL = new InjectionToken<string>('api.url');

// Use inject() inside the factory — no deps array needed
const apiUrlProvider = {
  provide: API_URL,
  useFactory: () => {
    const config = inject(AppConfig);
    return config.production
      ? 'https://api.prod.example.com'
      : 'https://api.dev.example.com';
  }
};

// Complex factory — all deps resolved via inject()
const httpClientProvider = {
  provide: HttpClient,
  useFactory: () => {
    const handler = inject(HttpHandler);
    const logger = inject(Logger);
    logger.log('Creating HTTP client');
    return new HttpClient(handler);
  }
};

useExisting - Alias Provider

typescript
import { Injectable, inject } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class NewLogger {
  log(message: string): void {
    console.log('[NEW]', message);
  }
}

// Alias an abstract token to the concrete implementation
export abstract class Logger {
  abstract log(message: string): void;
}

const loggerAlias: Provider = {
  provide: Logger,
  useExisting: NewLogger
};

// Usage
export class MyComponent {
  private readonly logger = inject(Logger);

  constructor() {
    this.logger.log('Using aliased logger');
  }
}

Injection Tokens

InjectionToken - Type-Safe Tokens

typescript
import { InjectionToken, inject } from '@angular/core';

// Primitive token
export const MAX_RETRIES = new InjectionToken<number>('max.retries', {
  providedIn: 'root',
  factory: () => 3 // Default value
});

// Object token
export interface FeatureFlags {
  enableNewUI: boolean;
  enableBeta: boolean;
}

export const FEATURE_FLAGS = new InjectionToken<FeatureFlags>(
  'feature.flags',
  {
    providedIn: 'root',
    factory: () => ({
      enableNewUI: false,
      enableBeta: false
    })
  }
);

// Usage via inject()
@Injectable()
export class ApiService {
  private readonly maxRetries = inject(MAX_RETRIES);
  private readonly flags = inject(FEATURE_FLAGS);
}

Hierarchical Injectors

Root Injector

typescript
// Singleton across entire app
@Injectable({
  providedIn: 'root'
})
export class GlobalService {
  private state = {};
}

Component Injector

typescript
@Injectable()
export class ComponentService {
  private data = [];
}

@Component({
  selector: 'app-my-component',
  standalone: true,
  template: '...',
  providers: [ComponentService] // New instance per component
})
export class MyComponent {
  private readonly service = inject(ComponentService);
}

// Each component instance gets its own service instance

Element Injector

typescript
@Directive({
  selector: '[appHighlight]',
  standalone: true,
  providers: [DirectiveService]
})
export class HighlightDirective {
  private readonly service = inject(DirectiveService);
}

ProvidedIn Options

typescript
// Root - singleton across entire app
@Injectable({
  providedIn: 'root'
})
export class RootService {}

// Platform - shared across multiple apps
@Injectable({
  providedIn: 'platform'
})
export class PlatformService {}

Optional and Scoped Injection

Use inject() options instead of @Optional, @Self, @SkipSelf, @Host:

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

export class MyService {
  // @Optional() equivalent
  private readonly logger = inject(Logger, { optional: true });

  // @Self() equivalent — only from this component's injector
  private readonly local = inject(LocalService, { self: true });

  // @SkipSelf() equivalent — skip this injector, look up the tree
  private readonly parent = inject(SharedService, { skipSelf: true });

  // @Host() equivalent — stop at host element
  private readonly host = inject(ParentComponent, { host: true });

  // Combine options
  readonly #dep = inject(Dep, {
    optional: true,
    self: true,
  });

  constructor() {
    this.logger?.log('Service created');
  }
}

Environment Providers (replaces ForRoot/ForChild)

Use makeEnvironmentProviders and provideX() functions instead of NgModule.forRoot() / NgModule.forChild():

typescript
import { makeEnvironmentProviders, EnvironmentProviders } from '@angular/core';

export interface SharedConfig {
  apiUrl: string;
}

export const SHARED_CONFIG = new InjectionToken<SharedConfig>('shared.config');

// Replace forRoot() with a provideX() function
export function provideShared(config: SharedConfig): EnvironmentProviders {
  return makeEnvironmentProviders([
    SharedService,
    {
      provide: SHARED_CONFIG,
      useValue: config
    }
  ]);
}

// In bootstrapApplication (app root)
bootstrapApplication(AppComponent, {
  providers: [
    provideShared({ apiUrl: 'https://api.example.com' }),
    provideRouter(routes),
    provideHttpClient()
  ]
});

// In lazy-loaded routes — child-scope providers
export const routes: Routes = [
  {
    path: 'feature',
    loadComponent: () => import('./feature.component'),
    providers: [FeatureScopedService]
  }
];

Multi-Providers

typescript
import { InjectionToken, inject } from '@angular/core';

export const HTTP_INTERCEPTORS =
  new InjectionToken<HttpInterceptor[]>('http.interceptors');

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    return next.handle(req);
  }
}

@Injectable()
export class LoggingInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    return next.handle(req);
  }
}

// Register as multi-providers
const providers: Provider[] = [
  {
    provide: HTTP_INTERCEPTORS,
    useClass: AuthInterceptor,
    multi: true
  },
  {
    provide: HTTP_INTERCEPTORS,
    useClass: LoggingInterceptor,
    multi: true
  }
];

// Inject as array
export class HttpService {
  private readonly interceptors = inject(HTTP_INTERCEPTORS);
}

Tree-Shakable Providers

typescript
// Tree-shakable (preferred) — service is removed if never injected
@Injectable({
  providedIn: 'root'
})
export class NewService {}

Testing with DI

TestBed Provider Overrides

typescript
import { TestBed } from '@angular/core/testing';

describe('MyComponent', () => {
  let mockUserService: jasmine.SpyObj<UserService>;

  beforeEach(() => {
    mockUserService = jasmine.createSpyObj('UserService', ['getUsers']);

    TestBed.configureTestingModule({
      imports: [MyComponent], // standalone component
      providers: [
        { provide: UserService, useValue: mockUserService }
      ]
    });
  });

  it('should get users', () => {
    mockUserService.getUsers.and.returnValue([]);
    const fixture = TestBed.createComponent(MyComponent);
    // Test component with mock
  });
});

Spy on Dependencies

typescript
import { TestBed } from '@angular/core/testing';

describe('UserService', () => {
  let service: UserService;
  let httpMock: jasmine.SpyObj<HttpClient>;

  beforeEach(() => {
    httpMock = jasmine.createSpyObj('HttpClient', ['get', 'post']);

    TestBed.configureTestingModule({
      providers: [
        UserService,
        { provide: HttpClient, useValue: httpMock }
      ]
    });

    service = TestBed.inject(UserService);
  });

  it('should fetch users', () => {
    httpMock.get.and.returnValue(of([]));
    service.getUsers().subscribe();
    expect(httpMock.get).toHaveBeenCalled();
  });
});

When to Use This Skill

Use angular-dependency-injection when building modern, production-ready applications that require:

  • Modular service architecture
  • Testable components and services
  • Configuration management
  • Plugin/extension systems
  • Multi-provider patterns (interceptors, validators)
  • Complex service hierarchies
  • Lazy-loaded route isolation
  • Tree-shakable code

Angular DI Best Practices

  1. Use inject() — Cleaner than constructor injection, works in class fields
  2. Use providedIn: 'root' — Tree-shakable and singleton
  3. Use InjectionToken — Type-safe tokens, no string tokens
  4. Use standalone components — Providers in @Component, not @NgModule
  5. Use provideX() functions — Replaces forRoot()/forChild()
  6. Use inject() in factories — No deps array needed
  7. Use inject() options — Replaces @Optional, @Self, @SkipSelf, @Host
  8. Favor composition — Inject small, focused services
  9. Test with mocks — Override providers in TestBed
  10. Avoid circular dependencies — Refactor to a common service

Resources

Câu hỏi thường gặp

Kỹ năng AI Angular Dependency Injection làm được gì?

Use when building modular Angular applications requiring dependency injection with providers, injectors, and services.

Vì sao nên dùng Angular Dependency Injection trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Angular Dependency Injection là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Angular Dependency Injection trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/TheBushidoCollective/han/tree/main/plugins/frameworks/angular/skills/angular-dependency-injection. TypingMind đọc tệp SKILL.md và cài đặt thành một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Angular Dependency Injection?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Bạn có thể dùng Angular Dependency Injection với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Angular Dependency Injection với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Angular Dependency Injection có miễn phí không?

Kỹ năng này được TheBushidoCollective phát hành trên GitHub. Hãy xem điều khoản giấy phép trong kho mã. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp cho mô hình các công cụ mới để gọi — mã được chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và tiêu chí của đầu ra tốt. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇