Token导航 LogoToken导航TokenDH.com
研究检索权限需确认github未标认证来源可访问clear审计未展示

debug_angular调试 Angular

Agent Skill

debug_angular 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

1,042

周安装

43

GitHub Stars

公开资料未说明

下载量

341
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:debug_angular(调试 Angular)
来源仓库:https://github.com/snakeo/claude-debug-and-refactor-skills-plugin
仓库路径:skills/debug_angular
安装命令:
npx skills add snakeo/claude-debug-and-refactor-skills-plugin --skill "debug:angular"
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

AgentSkills.tonpx skills
npx skills add snakeo/claude-debug-and-refactor-skills-plugin --skill "debug:angular"

简介

debug_angular 辅助调试 Angular 项目,支持代码分析与问题定位。

  • 适用于 Codex、Claude、Cursor 和 Gemini CLI 环境中的前端开发。
  • 通过 npx 命令安装,路径为 snakeo/claude-debug-and-refactor-skills-plugin。
  • 使用前需确认项目依赖和构建配置,防止误改关键逻辑。
  • 建议结合本地测试验证修改效果,确保稳定性。

SKILL.md

Angular Debugging Guide

This guide provides a systematic approach to debugging Angular applications, covering common error patterns, debugging tools, and structured resolution phases.

Common Error Patterns

NullInjectorError

Symptoms:

  • NullInjectorError: No provider for <ServiceName>
  • StaticInjectorError: No provider for <ServiceName>
  • Service injection fails at runtime

Root Causes:

  1. Service not provided in any module or component
  2. Circular dependency between services
  3. Missing @Injectable() decorator
  4. Service provided in wrong scope (lazy-loaded module vs root)

Solutions:

// Solution 1: Provide in root (recommended for singletons)
@Injectable({
  providedIn: 'root'
})
export class MyService { }

// Solution 2: Provide in specific module
@NgModule({
  providers: [MyService]
})
export class FeatureModule { }

// Solution 3: Provide in component (new instance per component)
@Component({
  providers: [MyService]
})
export class MyComponent { }

ExpressionChangedAfterItHasBeenCheckedError (NG0100)

Symptoms:

  • Error appears only in development mode
  • Typically occurs in ngAfterViewInit or ngAfterContentInit
  • Value changes during change detection cycle

Root Causes:

  1. Modifying component state in lifecycle hooks after change detection
  2. Child component modifying parent state
  3. Async operations completing during change detection

Solutions:

// Solution 1: Use setTimeout to defer change
ngAfterViewInit() {
  setTimeout(() => {
    this.value = 'new value';
  });
}

// Solution 2: Use ChangeDetectorRef
constructor(private cdr: ChangeDetectorRef) {}

ngAfterViewInit() {
  this.value = 'new value';
  this.cdr.detectChanges();
}

// Solution 3: Use async pipe (preferred for observables)
// In template: {{ value$ | async }}
value$ = this.service.getValue();

Common NG Error Codes (NG0100-NG0999)

Error CodeDescriptionCommon Fix
NG0100Expression changed after checkedUse detectChanges() or setTimeout
NG0200Circular dependency in DIRefactor service dependencies
NG0201No provider for serviceAdd to providers array or use providedIn
NG0300Multiple components match selectorMake selectors more specific
NG0301Export not foundCheck export name in directive/component
NG0302Pipe not foundImport module containing pipe
NG0303No matching elementCheck selector syntax
NG0500Hydration mismatch (SSR)Ensure server/client render same content
NG0910Unsafe bindingSanitize or use bypassSecurityTrust*
NG0912Component ID collisionUnique component selectors

RxJS Subscription Leaks

Symptoms:

  • Memory leaks in long-running applications
  • Console warnings about destroyed components
  • Multiple HTTP requests for same data
  • Performance degradation over time

Detection:

// Use takeUntilDestroyed (Angular 16+)
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';

@Component({...})
export class MyComponent {
  private destroyRef = inject(DestroyRef);

  ngOnInit() {
    this.service.getData()
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(data => this.data = data);
  }
}

// Legacy approach with Subject
private destroy$ = new Subject<void>();

ngOnInit() {
  this.service.getData()
    .pipe(takeUntil(this.destroy$))
    .subscribe();
}

ngOnDestroy() {
  this.destroy$.next();
  this.destroy$.complete();
}

RxJS Debugging Operators:

import { tap } from 'rxjs/operators';

this.data$.pipe(
  tap({
    next: v => console.log('Value:', v),
    error: e => console.error('Error:', e),
    complete: () => console.log('Complete')
  })
).subscribe();

Lazy Loading Failures

Symptoms:

  • ChunkLoadError in console
  • Module fails to load on navigation
  • Network errors for chunk files

Common Causes:

  1. Incorrect path in loadChildren
  2. Missing default export
  3. Network/CDN issues
  4. Cache issues after deployment

Solutions:

// Correct lazy loading syntax (Angular 14+)
const routes: Routes = [
  {
    path: 'feature',
    loadChildren: () => import('./feature/feature.module')
      .then(m => m.FeatureModule)
  },
  // Standalone components (Angular 15+)
  {
    path: 'standalone',
    loadComponent: () => import('./standalone/standalone.component')
      .then(c => c.StandaloneComponent)
  }
];

// Handle chunk load errors
// In app.component.ts or error handler
constructor(private router: Router) {
  this.router.events.subscribe(event => {
    if (event instanceof NavigationError) {
      if (event.error.name === 'ChunkLoadError') {
        window.location.reload();
      }
    }
  });
}

Zone.js Issues

Symptoms:

  • Change detection not triggering
  • UI not updating after async operations
  • runOutsideAngular causing update issues

Solutions:

constructor(private ngZone: NgZone) {}

// Force change detection inside Angular zone
ngOnInit() {
  someExternalLibrary.onEvent((data) => {
    this.ngZone.run(() => {
      this.data = data;
    });
  });
}

// Optimize by running outside zone (for performance-critical code)
runHeavyComputation() {
  this.ngZone.runOutsideAngular(() => {
    // Heavy computation that doesn't need CD
    const result = this.compute();

    // Re-enter zone when updating UI
    this.ngZone.run(() => {
      this.result = result;
    });
  });
}

Zoneless Angular (Angular 18+)

// For zoneless applications, use signals
import { signal, computed, effect } from '@angular/core';

@Component({
  selector: 'app-zoneless',
  template: `<p>Count: {{ count() }}</p>`
})
export class ZonelessComponent {
  count = signal(0);
  doubled = computed(() => this.count() * 2);

  increment() {
    this.count.update(c => c + 1);
  }
}

Debugging Tools

Angular DevTools

Installation:

Features:

  1. Component Explorer: Inspect component tree, inputs, outputs, and state
  2. Profiler: Record and analyze change detection cycles
  3. Dependency Injection Graph: Visualize injector hierarchy
  4. Router Tree: Debug routing configuration

Requirements:

  • Application must be in development mode (ng serve)
  • For deployed apps, build with optimization: false

ng.probe() (Console Debugging)

// In browser console

// Get component instance from DOM element
ng.getComponent($0);

// Get directive instances
ng.getDirectives($0);

// Get owning component
ng.getOwningComponent($0);

// Get injector
ng.getInjector($0);

// Trigger change detection
ng.applyChanges(component);

// Get context (for embedded views)
ng.getContext($0);

// Angular 14+ debugging utilities
const appRef = ng.getInjector(document.querySelector('app-root'))
  .get(ng.coreTokens.ApplicationRef);
appRef.tick(); // Force global change detection

Source Maps Configuration

// angular.json
{
  "projects": {
    "my-app": {
      "architect": {
        "build": {
          "configurations": {
            "development": {
              "sourceMap": true,
              "optimization": false,
              "extractLicenses": false,
              "namedChunks": true
            },
            "production": {
              "sourceMap": {
                "scripts": true,
                "styles": true,
                "hidden": true,
                "vendor": false
              }
            }
          }
        }
      }
    }
  }
}

Custom Error Handler

// global-error-handler.ts
import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  constructor(private injector: Injector) {}

  handleError(error: Error | HttpErrorResponse): void {
    if (error instanceof HttpErrorResponse) {
      // Server error
      console.error('HTTP Error:', error.status, error.message);
    } else {
      // Client error
      console.error('Client Error:', error.message);
      console.error('Stack:', error.stack);
    }

    // Log to external service
    const loggingService = this.injector.get(LoggingService);
    loggingService.logError(error);
  }
}

// app.module.ts
@NgModule({
  providers: [
    { provide: ErrorHandler, useClass: GlobalErrorHandler }
  ]
})
export class AppModule { }

HTTP Interceptor for Debugging

@Injectable()
export class DebugInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const started = Date.now();

    return next.handle(req).pipe(
      tap({
        next: (event) => {
          if (event instanceof HttpResponse) {
            const elapsed = Date.now() - started;
            console.log(`${req.method} ${req.urlWithParams} - ${elapsed}ms`);
          }
        },
        error: (error) => {
          console.error(`${req.method} ${req.urlWithParams} - Error:`, error);
        }
      })
    );
  }
}

The Four Phases of Angular Debugging

Phase 1: Reproduce and Isolate

Objective: Consistently reproduce the issue and narrow down the scope.

Steps:

  1. Reproduce the error - Get exact steps to trigger the issue
  2. Check the console - Note full error message and stack trace
  3. Identify the component - Which component/service is affected?
  4. Check recent changes - Use git diff to see what changed

Commands:

# Check recent changes
git diff HEAD~5 --name-only

# Check for TypeScript errors
ng build --configuration development 2>&1 | head -50

# Check for lint issues
ng lint

Console Investigation:

// Add strategic logging
console.group('Component State');
console.log('Inputs:', this.inputValue);
console.log('State:', this.state);
console.trace('Call stack');
console.groupEnd();

Phase 2: Analyze the Error

Objective: Understand exactly what is failing and why.

For DI Errors:

// Check injector hierarchy
const injector = TestBed.inject(Injector);
console.log('Providers:', injector);

// Verify service is provided
try {
  const service = TestBed.inject(MyService);
  console.log('Service found:', service);
} catch (e) {
  console.error('Service not found:', e);
}

For Change Detection Errors:

// Enable change detection debugging
import { enableDebugTools } from '@angular/platform-browser';

// In main.ts
platformBrowserDynamic().bootstrapModule(AppModule)
  .then(ref => {
    const appRef = ref.injector.get(ApplicationRef);
    const componentRef = appRef.components[0];
    enableDebugTools(componentRef);
    // Access via: window.ng.profiler.timeChangeDetection()
  });

For Template Errors:

// Use safe navigation operator
{{ user?.profile?.name }}

// Use @if with else block (Angular 17+)
@if (user) {
  <p>{{ user.name }}</p>
} @else {
  <p>Loading...</p>
}

// Use *ngIf with ng-template (legacy)
<p *ngIf="user; else loading">{{ user.name }}</p>
<ng-template #loading>Loading...</ng-template>

Phase 3: Apply the Fix

Objective: Implement and verify the solution.

Fix Patterns:

// Pattern 1: Safe observable handling
this.data$ = this.service.getData().pipe(
  catchError(error => {
    console.error('Data fetch failed:', error);
    return of(null); // Return fallback
  }),
  shareReplay(1) // Cache for multiple subscribers
);

// Pattern 2: Proper initialization
@Input() set items(value: Item[]) {
  this._items = value ?? [];
  this.updateView();
}
private _items: Item[] = [];

// Pattern 3: OnPush with immutability
@Component({
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class OptimizedComponent {
  @Input() data!: ReadonlyArray<Item>;

  updateData() {
    // Create new reference to trigger CD
    this.data = [...this.data, newItem];
  }
}

Verify the Fix:

# Run affected tests
ng test --include="**/affected.component.spec.ts"

# Run e2e tests
ng e2e --spec="affected.e2e-spec.ts"

# Build to check for compilation errors
ng build --configuration production

Phase 4: Prevent Regression

Objective: Add tests and monitoring to prevent recurrence.

Write Targeted Tests:

describe('BugfixComponent', () => {
  it('should handle null input gracefully', () => {
    component.data = null;
    fixture.detectChanges();
    expect(component.displayData).toEqual([]);
  });

  it('should unsubscribe on destroy', () => {
    const subscription = component['subscription'];
    spyOn(subscription, 'unsubscribe');
    component.ngOnDestroy();
    expect(subscription.unsubscribe).toHaveBeenCalled();
  });

  it('should handle HTTP errors', fakeAsync(() => {
    spyOn(service, 'getData').and.returnValue(
      throwError(() => new Error('Network error'))
    );
    component.loadData();
    tick();
    expect(component.error).toBe('Failed to load data');
  }));
});

Add Error Boundary:

// error-boundary.component.ts
@Component({
  selector: 'app-error-boundary',
  template: `
    @if (hasError) {
      <div class="error-fallback">
        <h2>Something went wrong</h2>
        <button (click)="retry()">Retry</button>
      </div>
    } @else {
      <ng-content></ng-content>
    }
  `
})
export class ErrorBoundaryComponent implements OnInit, ErrorHandler {
  hasError = false;

  handleError(error: Error): void {
    this.hasError = true;
    console.error('Error caught:', error);
  }

  retry(): void {
    this.hasError = false;
  }
}

Quick Reference Commands

Development

# Start development server
ng serve

# Start with specific configuration
ng serve --configuration=development

# Start with SSL
ng serve --ssl

# Open browser automatically
ng serve --open

# Specify port
ng serve --port 4201

# Disable host check (for mobile testing)
ng serve --host 0.0.0.0 --disable-host-check

Building

# Development build (with source maps)
ng build --configuration development

# Production build
ng build --configuration production

# Build with stats for bundle analysis
ng build --stats-json

# Analyze bundle
npx webpack-bundle-analyzer dist/my-app/stats.json

Testing

# Run all tests
ng test

# Run tests once (CI mode)
ng test --no-watch --code-coverage

# Run specific test file
ng test --include="**/my.component.spec.ts"

# Run with specific browsers
ng test --browsers=ChromeHeadless

# Debug tests in browser
ng test --browsers=Chrome

# E2E tests
ng e2e

Linting and Code Quality

# Run ESLint
ng lint

# Fix auto-fixable issues
ng lint --fix

# Check specific files
ng lint --files="src/app/my.component.ts"

Generating Code

# Generate component with tests
ng generate component my-component

# Generate service
ng generate service my-service

# Generate module with routing
ng generate module my-module --routing

# Dry run (preview changes)
ng generate component my-component --dry-run

Cache Management

# Clear Angular cache
ng cache clean

# Clear npm cache
npm cache clean --force

# Reinstall dependencies
rm -rf node_modules package-lock.json
npm install

Debugging Specific Issues

# Check Angular version
ng version

# Update Angular
ng update @angular/core @angular/cli

# Check for outdated packages
npm outdated

# Check TypeScript configuration
npx tsc --showConfig

# Check for circular dependencies
npx madge --circular src/

# Profile memory usage
node --inspect node_modules/.bin/ng serve

Performance Debugging

Profiling Change Detection

// Enable profiling in main.ts
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

platformBrowserDynamic().bootstrapModule(AppModule)
  .then(moduleRef => {
    const appRef = moduleRef.injector.get(ApplicationRef);
    const componentRef = appRef.components[0];

    // Enable debug tools
    enableDebugTools(componentRef);

    // In console: ng.profiler.timeChangeDetection()
  });

OnPush Optimization

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class PerformantComponent {
  // Use signals (Angular 16+) for reactive state
  count = signal(0);
  doubled = computed(() => this.count() * 2);

  // Or use observables with async pipe
  data$ = this.service.getData().pipe(
    shareReplay({ bufferSize: 1, refCount: true })
  );
}

TrackBy for Lists

@Component({
  template: `
    @for (item of items; track item.id) {
      <app-item [item]="item" />
    }
  `
})
export class ListComponent {
  items: Item[] = [];

  // Legacy ngFor syntax
  trackById(index: number, item: Item): number {
    return item.id;
  }
}

Resources

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Claude Code

29.68%
按下载量换算101

OpenCode

24.18%
按下载量换算82

Cursor

17.85%
按下载量换算61

Antigravity

11.93%
按下载量换算41

windsurf

8.55%
按下载量换算29

Codex

3.91%
按下载量换算13

安全审计

暂无安全审计结果可展示。

权限和风险

权限需确认

当前来源未能明确判断权限范围,默认进入异常复核队列。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills