mcpField
A
angular-http

angular-http

github.com/oguzhan18开发7185 次安装31 周前更新
代码仓库

关于 angular-http

面向 Angular HttpClient 开发的技能,涵盖 HTTP 请求、拦截器、请求上下文、取消请求和响应处理。

主要功能

  1. 01配置函数式拦截器
  2. 02通过 withFetch 使用 fetch
  3. 03设置单请求 HttpContext 元数据
  4. 04使用 AbortSignal 取消请求
  5. 05为响应添加类型并处理错误

适用场景

  1. 01为请求添加身份验证标头
  2. 02统一处理请求日志或错误
  3. 03在网络不稳定时重试请求
  4. 04取消请求或设置单请求标志

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/oguzhan18/angular-ecosystem-skills --skill angular-http

安装后在 Claude Code 中输入/angular-http确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/discussions/
_INDEX.md
references/docs/
_INDEX.md
references/issues/
_INDEX.md
references/releases/
_INDEX.md

详细介绍

@angular/common/http

版本: Angular 21(2025) 标签: HTTP、REST、API、拦截器

参考: HttpClient • API • 拦截器

API 变更

本节记录近期特定版本的 API 变更。

  • 新增:函数式拦截器——使用 provideHttpClient(withInterceptors([...])) 设置现代拦截器 来源

  • 新增:withFetch——在 HttpClient 中使用原生 fetch API 来源

  • 新增:withInterceptorsFromDi——通过函数式方式支持旧版拦截器

  • 新增:HttpContext 令牌——使用 HttpContextToken 设置单个请求的元数据

  • 新增:支持 AbortSignal——支持超时的请求取消

  • 已弃用:基于类的 HttpInterceptor——迁移到函数式拦截器

最佳实践

  • 使用函数式拦截器
// ✅ Modern functional interceptor
export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const authService = inject(AuthService);
  const token = authService.getToken();
  
  if (token) {
    const authReq = req.clone({
      setHeaders: { Authorization: `Bearer ${token}` }
    });
    return next(authReq);
  }
  return next(req);
};

// Register
export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(withInterceptors([authInterceptor]))
  ]
};
  • 使用拦截器处理横切关注点——身份验证、日志记录、错误处理
// Error interceptor with retry
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
  return next(req).pipe(
    catchError((error: HttpErrorResponse) => {
      if (error.status === 401) {
        inject(Router).navigate(['/login']);
      }
      return throwError(() => error);
    })
  );
};
  • 对不稳定网络使用带退避机制的重试
import { retry, delay, catchError } from 'rxjs/operators';

http.get('/api/data').pipe(
  retry({ count: 3, delay: 1000 })
);
  • 使用 HttpContext 设置单个请求的标记
const cacheToken = new HttpContextToken<boolean>(() => false);

export const cacheInterceptor: HttpInterceptorFn = (req, next) => {
  if (req.context.get(cacheToken)) {
    // Check cache
  }
  return next(req);
};

// Usage
http.get('/api/data', {
  context: new HttpContext().set(cacheToken, true)
});
  • 为 HTTP 响应使用正确的类型
interface User {
  id: number;
  name: string;
}

http.get<User>('/api/user/1').subscribe(user => {
  console.log(user.name); // TypeScript knows the type
});
  • 使用 observe: 'response' 获取完整的 HTTP 响应
http.get('/api/data', { observe: 'response' }).subscribe(response => {
  console.log(response.headers);
  console.log(response.body);
});
  • 全局处理错误
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  handleError(error: Error) {
    // Log to error tracking service
    console.error(error);
  }
}

// Register
provideErrorHandler(GlobalErrorHandler)
  • 对 CORS 请求使用 withCredentials
http.get('/api/data', { withCredentials: true });

评论

支持 Markdown