CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-angular--common--http

HTTP client API for Angular applications with XMLHttpRequest support, request/response interception, and testability features

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

Angular HTTP Client

Angular's HTTP client API provides a powerful, RxJS-based HTTP client for Angular applications. Built on XMLHttpRequest and Fetch API, it offers typed request/response objects, interceptors, error handling, and comprehensive testing support.

Package Information

  • Package Name: @angular/common
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @angular/common
  • Subpath: /http

Core Imports

import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { provideHttpClient, withInterceptors } from '@angular/common/http';

For specific functionality:

import { 
  HttpRequest, 
  HttpResponse, 
  HttpErrorResponse,
  HttpEventType 
} from '@angular/common/http';

Basic Usage

import { inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({})
export class MyComponent {
  private http = inject(HttpClient);

  // GET request
  getUsers() {
    return this.http.get<User[]>('/api/users');
  }

  // POST request with typed response
  createUser(user: CreateUserRequest) {
    return this.http.post<User>('/api/users', user);
  }

  // Request with headers and params
  searchUsers(query: string) {
    const headers = new HttpHeaders().set('Authorization', 'Bearer token');
    const params = new HttpParams().set('q', query);
    
    return this.http.get<User[]>('/api/users/search', { headers, params });
  }
}

Architecture

The Angular HTTP client is built around several key components:

  • HttpClient: Main service for making HTTP requests with full RxJS integration
  • Request/Response System: Strongly-typed request and response objects with immutable design
  • Interceptor Chain: Middleware pattern for cross-cutting concerns like authentication, logging, and caching
  • Backend Abstraction: Pluggable backends (XMLHttpRequest, Fetch API, JSONP) with consistent interface
  • Provider System: Modern dependency injection configuration with feature flags
  • Context System: Type-safe request-scoped data sharing mechanism

Capabilities

HTTP Client Service

Core HTTP client service providing typed request methods with RxJS observables and comprehensive options support.

@Injectable({providedIn: 'root'})
class HttpClient {
  request<R>(req: HttpRequest<any>): Observable<HttpEvent<R>>;
  request(method: string, url: string, options?: RequestOptions): Observable<any>;
  
  get<T>(url: string, options?: RequestOptions): Observable<T>;
  post<T>(url: string, body: any, options?: RequestOptions): Observable<T>;
  put<T>(url: string, body: any, options?: RequestOptions): Observable<T>;
  patch<T>(url: string, body: any, options?: RequestOptions): Observable<T>;
  delete<T>(url: string, options?: RequestOptions): Observable<T>;
  head<T>(url: string, options?: RequestOptions): Observable<T>;
  options<T>(url: string, options?: RequestOptions): Observable<T>;
  jsonp<T>(url: string, callbackParam: string): Observable<T>;
}

interface RequestOptions {
  headers?: HttpHeaders | Record<string, string | string[]>;
  params?: HttpParams | Record<string, string | number | boolean | ReadonlyArray<string | number | boolean>>;
  context?: HttpContext;
  observe?: 'body' | 'events' | 'response';
  responseType?: 'arraybuffer' | 'blob' | 'json' | 'text';
  reportProgress?: boolean;
  withCredentials?: boolean;
  credentials?: RequestCredentials;
  transferCache?: {includeHeaders?: string[]} | boolean;
  timeout?: number;
  keepalive?: boolean;
  priority?: RequestPriority;
  cache?: RequestCache;
  mode?: RequestMode;
  redirect?: RequestRedirect;
  referrer?: string;
  integrity?: string;
}

Request and Response Objects

Immutable request and response objects with comprehensive type safety and configuration options.

class HttpRequest<T> {
  readonly method: string;
  readonly url: string;
  readonly urlWithParams: string;
  readonly body: T | null;
  readonly headers: HttpHeaders;
  readonly params: HttpParams;
  readonly context: HttpContext;
  readonly reportProgress: boolean;
  readonly responseType: 'arraybuffer' | 'blob' | 'json' | 'text';
  readonly withCredentials: boolean;
  readonly credentials: RequestCredentials;
  readonly keepalive: boolean;
  readonly priority: RequestPriority;
  readonly cache: RequestCache;
  readonly mode: RequestMode;
  readonly redirect: RequestRedirect;
  readonly referrer: string;
  readonly integrity: string;
  readonly transferCache?: {includeHeaders?: string[]} | boolean;
  readonly timeout?: number;
  
  clone(update?: Partial<HttpRequest<any>>): HttpRequest<T>;
  serializeBody(): ArrayBuffer | Blob | FormData | URLSearchParams | string | null;
}

class HttpResponse<T> extends HttpResponseBase {
  readonly body: T | null;
  readonly headers: HttpHeaders;
  readonly status: number;
  readonly statusText: string;
  readonly url: string | null;
  readonly ok: boolean;
  readonly type: HttpEventType.Response;
  readonly redirected?: boolean;
  readonly responseType?: ResponseType;
  
  clone(update?: Partial<HttpResponse<any>>): HttpResponse<T>;
}

class HttpErrorResponse extends HttpResponseBase implements Error {
  readonly name: string;
  readonly message: string;
  readonly error: any | null;
  readonly ok: boolean;
}

Headers and Parameters

Immutable, fluent APIs for managing HTTP headers and URL parameters with full type safety.

class HttpHeaders {
  constructor(headers?: string | {[name: string]: string | number | (string | number)[]} | Headers);
  
  has(name: string): boolean;
  get(name: string): string | null;
  getAll(name: string): string[] | null;
  keys(): string[];
  append(name: string, value: string | string[]): HttpHeaders;
  set(name: string, value: string | string[]): HttpHeaders;
  delete(name: string, value?: string | string[]): HttpHeaders;
}

class HttpParams {
  constructor(options?: HttpParamsOptions);
  
  has(param: string): boolean;
  get(param: string): string | null;
  getAll(param: string): string[] | null;
  keys(): string[];
  append(param: string, value: string | number | boolean): HttpParams;
  appendAll(params: {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}): HttpParams;
  set(param: string, value: string | number | boolean): HttpParams;
  delete(param: string, value?: string | number | boolean): HttpParams;
  toString(): string;
}

interface HttpParamsOptions {
  fromString?: string;
  fromObject?: {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>};
  encoder?: HttpParameterCodec;
}

HTTP Interceptors

Middleware system for cross-cutting concerns with both functional and class-based approaches.

type HttpInterceptorFn = (
  req: HttpRequest<unknown>,
  next: HttpHandlerFn,
) => Observable<HttpEvent<unknown>>;

type HttpHandlerFn = (req: HttpRequest<unknown>) => Observable<HttpEvent<unknown>>;

interface HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>;
}

const HTTP_INTERCEPTORS: InjectionToken<readonly HttpInterceptor[]>;

Provider Configuration

Modern dependency injection configuration with feature flags and composable setup.

function provideHttpClient(...features: HttpFeature<HttpFeatureKind>[]): EnvironmentProviders;

function withInterceptors(interceptorFns: HttpInterceptorFn[]): HttpFeature<HttpFeatureKind.Interceptors>;
function withInterceptorsFromDi(): HttpFeature<HttpFeatureKind.LegacyInterceptors>;
function withFetch(): HttpFeature<HttpFeatureKind.Fetch>;
function withJsonpSupport(): HttpFeature<HttpFeatureKind.JsonpSupport>;
function withXsrfConfiguration(options: {cookieName?: string; headerName?: string}): HttpFeature<HttpFeatureKind.CustomXsrfConfiguration>;
function withNoXsrfProtection(): HttpFeature<HttpFeatureKind.NoXsrfProtection>;
function withRequestsMadeViaParent(): HttpFeature<HttpFeatureKind.RequestsMadeViaParent>;

enum HttpFeatureKind {
  Interceptors,
  LegacyInterceptors,
  CustomXsrfConfiguration,
  NoXsrfProtection,
  JsonpSupport,
  RequestsMadeViaParent,
  Fetch,
}

Context System

Type-safe mechanism for sharing data across the request lifecycle with token-based access.

class HttpContext {
  set<T>(token: HttpContextToken<T>, value: T): HttpContext;
  get<T>(token: HttpContextToken<T>): T;
  delete(token: HttpContextToken<unknown>): HttpContext;
  has(token: HttpContextToken<unknown>): boolean;
  keys(): IterableIterator<HttpContextToken<unknown>>;
}

class HttpContextToken<T> {
  constructor(public readonly defaultValue: () => T);
}

HTTP Resource API (Experimental)

Signal-based reactive HTTP resource for automatic request management and caching using Angular's Resource system.

const httpResource: HttpResourceFn;

interface HttpResourceFn {
  <T>(request: HttpResourceRequest, options?: HttpResourceOptions): HttpResourceRef<T>;
  arrayBuffer(request: HttpResourceRequest, options?: HttpResourceOptions): HttpResourceRef<ArrayBuffer>;
  blob(request: HttpResourceRequest, options?: HttpResourceOptions): HttpResourceRef<Blob>;
  text(request: HttpResourceRequest, options?: HttpResourceOptions): HttpResourceRef<string>;
}

interface HttpResourceRequest {
  url: string | Signal<string>;
  method?: string;
  body?: any;
  headers?: HttpHeaders | Record<string, string | string[]>;
  params?: HttpParams | Record<string, string | number | boolean | ReadonlyArray<string | number | boolean>>;
}

interface HttpResourceOptions {
  injector?: Injector;
}

interface HttpResourceRef<T> extends ResourceRef<T> {
  readonly headers: Signal<HttpHeaders | undefined>;
  readonly progress: Signal<HttpProgressEvent | undefined>;
  readonly statusCode: Signal<number | undefined>;
}

interface HttpTransferCacheOptions {
  includeHeaders?: string[];
}

Types

type HttpEvent<T> = 
  | HttpSentEvent
  | HttpHeaderResponse  
  | HttpResponse<T>
  | HttpDownloadProgressEvent
  | HttpUploadProgressEvent
  | HttpUserEvent<T>;

enum HttpEventType {
  Sent,
  UploadProgress,
  ResponseHeader, 
  DownloadProgress,
  Response,
  User
}

enum HttpStatusCode {
  Continue = 100,
  SwitchingProtocols = 101,
  Processing = 102,
  EarlyHints = 103,
  Ok = 200,
  Created = 201,
  Accepted = 202,
  NonAuthoritativeInformation = 203,
  NoContent = 204,
  ResetContent = 205,
  PartialContent = 206,
  MultiStatus = 207,
  AlreadyReported = 208,
  ImUsed = 226,
  MultipleChoices = 300,
  MovedPermanently = 301,
  Found = 302,
  SeeOther = 303,
  NotModified = 304,
  UseProxy = 305,
  Unused = 306,
  TemporaryRedirect = 307,
  PermanentRedirect = 308,
  BadRequest = 400,
  Unauthorized = 401,
  PaymentRequired = 402,
  Forbidden = 403,
  NotFound = 404,
  MethodNotAllowed = 405,
  NotAcceptable = 406,
  ProxyAuthenticationRequired = 407,
  RequestTimeout = 408,
  Conflict = 409,
  Gone = 410,
  LengthRequired = 411,
  PreconditionFailed = 412,
  PayloadTooLarge = 413,
  UriTooLong = 414,
  UnsupportedMediaType = 415,
  RangeNotSatisfiable = 416,
  ExpectationFailed = 417,
  ImATeapot = 418,
  MisdirectedRequest = 421,
  UnprocessableEntity = 422,
  Locked = 423,
  FailedDependency = 424,
  TooEarly = 425,
  UpgradeRequired = 426,
  PreconditionRequired = 428,
  TooManyRequests = 429,
  RequestHeaderFieldsTooLarge = 431,
  UnavailableForLegalReasons = 451,
  InternalServerError = 500,
  NotImplemented = 501,
  BadGateway = 502,
  ServiceUnavailable = 503,
  GatewayTimeout = 504,
  HttpVersionNotSupported = 505,
  VariantAlsoNegotiates = 506,
  InsufficientStorage = 507,
  LoopDetected = 508,
  NotExtended = 510,
  NetworkAuthenticationRequired = 511
}

interface HttpParameterCodec {
  encodeKey(key: string): string;
  encodeValue(value: string): string;
  decodeKey(key: string): string;
  decodeValue(value: string): string;
}

interface HttpTransferCacheOptions {
  includeHeaders?: string[];
}
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@angular/common@21.0.x#http
Publish Source
CLI
Badge
tessl/npm-angular--common--http badge