Using @ngify/http Reactive HTTP Client in Angular: Features, Usage, and Configuration
This article introduces the @ngify/http library as a RxJS‑based, Angular‑compatible HTTP client, compares it with axios and Angular HttpClient, explains its core features, shows installation and basic usage, and details advanced topics such as request/response interceptors, XSRF protection, and global configuration.
In front‑end development, the most widely used HTTP client is axios , which is Promise‑based. Its predecessor was AngularJS's $http service, and the design of axios was inspired by extracting $http from AngularJS to provide an independent service.
Reliability
@ngify/http adopts the same strict unit tests as Angular HttpClient, ensuring code quality and stability across various scenarios.
Basic Usage
import { HttpClient } from '@ngify/http';
const http = new HttpClient();
http.get('/api').subscribe();Unlike most HTTP libraries, @ngify/http is based on RxJS Observable instead of Promises, allowing direct use of RxJS operators for common request scenarios such as timeout, retry, and concurrency.
Timeout: import { timeout } from 'rxjs'; http.get('/api').pipe( timeout(5000) ).subscribe(...);
Retry: import { retry } from 'rxjs'; http.get('/api').pipe( retry(3) ).subscribe(...);
Concurrency: import { from, mergeAll } from 'rxjs'; const requests = [http.get('/api'), ...]; const concurrent = 2; // concurrency limit from(requests).pipe( mergeAll(concurrent) ).subscribe(...);
Installation
npm install @ngify/httpMaking Requests
The HttpClient provides methods corresponding to HTTP verbs; each method returns an Observable that sends the request upon subscription and emits the server response.
Getting JSON Data
http.get
('/api/config').subscribe(config => {
// process the configuration
});You can specify a generic type to indicate the expected response shape; if omitted, the response type defaults to any . For unknown shapes, using unknown is safer.
Getting Other Types of Data
By setting the responseType option, you can request 'text' , 'blob' , or 'arraybuffer' responses. Example for downloading an image as an ArrayBuffer :
http.get('/images/dog.jpg', { responseType: 'arraybuffer' }).subscribe(buffer => {
console.log('The image is ' + buffer.byteLength + ' bytes large');
});Changing Server State
http.post
('/api/config', newConfig).subscribe(config => {
console.log('Updated config:', config);
});The request body can be a string, number, boolean, array, object, ArrayBuffer , Blob , FormData , or URL‑encoded parameters, and HttpClient will serialize it accordingly.
Setting URL Parameters
http.get('/api/config', {
params: { filter: 'all' }
}).subscribe(config => {
// ...
});
http.post('/api/config', body, {
params: { filter: 'all' }
}).subscribe(config => {
// ...
});Setting Request Headers
http.get('/api/config', {
headers: {
'X-Debug-Level': 'verbose',
}
}).subscribe(config => {
// ...
});For more control, you can pass an instance of HttpHeaders , which is immutable; methods like append() return a new instance.
Intercepting Requests and Responses
HttpClient supports interceptors, which act as middleware to handle common patterns such as authentication, retry, caching, logging, and more.
Defining an Interceptor
export function loggingInterceptor(req: HttpRequest
, next: HttpHandlerFn): Observable
> {
console.log(req.url);
return next(req);
}Configuring Interceptors
const http = new HttpClient(
withInterceptors([loggingInterceptor, cachingInterceptor])
);Interceptors are chained in the order provided. They can also inspect and modify responses by checking event.type within the observable pipeline.
Modifying Requests
const reqWithHeader = req.clone({
headers: req.headers.set('X-New-Header', 'new header value'),
});Both HttpRequest and HttpResponse are immutable; changes are applied via .clone() .
Context Tokens
export const CACHING_ENABLED = new HttpContextToken
(() => true);Tokens stored in HttpContext allow per‑request metadata, such as enabling or disabling caching.
Class‑Based Interceptors
export class LoggingInterceptor implements HttpInterceptor {
intercept(req: HttpRequest
, handler: HttpHandler): Observable
> {
console.log('Request URL: ' + req.url);
return handler.handle(req);
}
}Switching HTTP Implementations
@ngify/http provides several backends: withXhr (XMLHttpRequest), withFetch (Fetch API), withWx (WeChat Mini‑Program), withTaro , and withUni . You can also supply a custom HttpBackend implementation.
import { withXhr, withFetch } from '@ngify/http';
import { withWx } from '@ngify/http-wx';
const xhrHttp = new HttpClient(withXhr());
const fetchHttp = new HttpClient(withFetch());
const wxHttp = new HttpClient(withWx());XSRF/CSRF Protection
The client can automatically read a cookie (default XSRF‑TOKEN ) and add it as a header (default X‑XSRF‑TOKEN ) for state‑changing requests, mitigating CSRF attacks.
const http = new HttpClient(
withXsrfProtection()
);Custom cookie and header names can be provided via withXsrfProtection({ cookieName, headerName }) . Protection is applied to non‑GET/HEAD relative URLs only.
Global Configuration
setupHttpClient(
withFetch(),
withXsrfProtection(),
);Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.