angular-http

v2026.09.24

Angular HttpClient with interceptors, error handling, retry, and caching patterns. Covers functional interceptors and typed responses. USE WHEN: user mentions "HttpClient", "Angular HTTP", "interceptors", "API calls", "Angular REST", "HTTP error handling", "auth interceptor" DO NOT USE FOR: Axios - use `axios` skill, Fetch API directly, backend HTTP frameworks

GitHub
安装命令
npx skhub add claude-dev-suite/angular-http
Markdown
SKILL.md

Angular HTTP - Quick Reference

Deep Knowledge: Use mcp__documentation__fetch_docs with technology: angular, topic: http for comprehensive documentation.

HttpClient Setup

// app.config.ts
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { authInterceptor } from './core/interceptors/auth.interceptor';
import { errorInterceptor } from './core/interceptors/error.interceptor';

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(withInterceptors([authInterceptor, errorInterceptor])),
  ]
};

Functional Interceptors (Angular 15+)

// Auth interceptor
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = inject(AuthService).getToken();
  if (token) {
    req = req.clone({
      setHeaders: { Authorization: `Bearer ${token}` },
    });
  }
  return next(req);
};

// Error interceptor
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
  return next(req).pipe(
    catchError((error: HttpErrorResponse) => {
      if (error.status === 401) {
        inject(Router).navigate(['/login']);
      }
      return throwError(() => error);
    })
  );
};

// Loading interceptor
export const loadingInterceptor: HttpInterceptorFn = (req, next) => {
  const loading = inject(LoadingService);
  loading.show();
  return next(req).pipe(finalize(() => loading.hide()));
};

Service Pattern with Error Handling

@Injectable({ providedIn: 'root' })
export class UserService {
  private http = inject(HttpClient);
  private baseUrl = '/api/users';

  getUsers(): Observable<User[]> {
    return this.http.get<User[]>(this.baseUrl).pipe(
      retry({ count: 2, delay: 1000 }),
      catchError(this.handleError),
    );
  }

  create(user: CreateUserDto): Observable<User> {
    return this.http.post<User>(this.baseUrl, user).pipe(
      catchError(this.handleError),
    );
  }

  private handleError(error: HttpErrorResponse): Observable<never> {
    let message = 'An error occurred';
    if (error.status === 0) {
      message = 'Network error';
    } else if (error.status === 404) {
      message = 'Resource not found';
    }
    return throwError(() => new Error(message));
  }
}

Typed Responses

// With observe: 'response' for full response
getWithHeaders(): Observable<HttpResponse<User[]>> {
  return this.http.get<User[]>(this.baseUrl, { observe: 'response' });
}

// With params
search(query: string, page: number): Observable<PaginatedResult<User>> {
  const params = new HttpParams()
    .set('q', query)
    .set('page', page.toString());
  return this.http.get<PaginatedResult<User>>(this.baseUrl, { params });
}

Anti-Patterns

Anti-PatternWhy It's BadCorrect Approach
Class-based interceptorsVerbose, deprecatedUse functional HttpInterceptorFn
Not typing responsesNo compile-time checksUse http.get<Type>()
Subscribing in servicesTight couplingReturn observables, subscribe in components
No error handlingSilent failuresUse catchError in service

Quick Troubleshooting

IssueLikely CauseSolution
HTTP call not firingForgot to subscribeSubscribe to the observable
Interceptor not runningNot in providersAdd to withInterceptors()
CORS errorBackend configConfigure CORS on server
Wrong content typeMissing headerHttpClient sets JSON by default
发现
标签

此技能尚未发布标签。

版本
最新版本元数据

版本

v2026.09.24

发布时间

2026年9月24日

分类

未分类

许可证

MIT

源路径

skills/frontend-frameworks/angular-http

默认分支

main

最新提交

9496306

Tree SHA

fe4e2f1