DevExtreme Angular - Intercept HTTP Requests
HTTP request interception in DevExtreme components might be useful for the following cases:
Intercept errors to display more informative messages to a user.
Inject an authentication token in the Authorization header.
Log API requests and responses for debugging or usage analysis.
Track upload progress and display a progress bar.
In Angular apps, you can use HttpInterceptor to intercept Ajax requests in DevExtreme components such as DataSource, FileUploader, and Map. This task requires that you import DxHttpModule
.
DxHttpModule
, Angular restricts access to XMLHttpRequest. This means you cannot get the XHR object in functions such as ODataContext.errorHandler, FileManager.fileSystemProvider.beforeAjaxSend, FileUploader.onUploadStarted, etc.The following code snippet demonstrates how to intercept a request in DataSource:
- import { Component, effect, signal } from '@angular/core';
- import DataSource from 'devextreme/data/data_source';
- import ODataStore from 'devextreme/data/odata/store';
- import { DxTreeViewModule } from 'devextreme-angular';
- import { DxHttpModule } from 'devextreme-angular/http';
- @Component({
- selector: 'app-root',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.css'],
- providers: [],
- standalone: true,
- imports: [DxHttpModule, DxTreeViewModule],
- })
- export class AppComponent {
- title = 'DxHttpModule Example';
- dataSource = new DataSource({
- onLoadError: (error) => {
- if (error.message) {
- this.loadError.set(error.message);
- }
- },
- store: new ODataStore({
- version: 2,
- url: 'http://www.example.com/Northwind.svc',
- }),
- });
- loadError = signal('');
- noDataText = '';
- constructor() {
- effect(() => {
- this.noDataText = this.loadError();
- });
- this.dataSource.load().then((data) => {
- console.log('DataSource is loaded:', data);
- });
- }
- }
- import { Injectable } from '@angular/core';
- import { throwError } from 'rxjs';
- import {
- HttpHandler,
- HttpInterceptor,
- HttpRequest,
- } from '@angular/common/http';
- @Injectable()
- export class LoggingInterceptor implements HttpInterceptor {
- intercept(req: HttpRequest<any>, next: HttpHandler) {
- // to show that request is intercepted, a permission access error is raised
- return throwError(() => ({
- status: 403,
- statusText: 'Request intercepted. Access Denied',
- }));
- // return next.handle(req);
- }
- }
- import { bootstrapApplication } from '@angular/platform-browser';
- import { AppComponent } from './app/app.component';
- import { HTTP_INTERCEPTORS } from '@angular/common/http';
- import { LoggingInterceptor } from './app/interceptors';
- bootstrapApplication(AppComponent, {
- providers: [
- { provide: HTTP_INTERCEPTORS, useClass: LoggingInterceptor, multi: true },
- ],
- });
If you have technical questions, please create a support ticket in the DevExpress Support Center.