Screen the $http request information prior to transmission

Angular has a built-in feature that removes properties with a prefix of $$ from request data or params objects.

I want to filter out my own UI-specific properties that I don't want to send to the server, but I don't want to rely on using $$.

Is there a way to access Angular's $$ filter method publicly to filter objects with a different prefix?

Where would be the most appropriate place to implement this method? Should I use a Transform or an Interceptor?

For example, consider the following data object:

var payload = {
    id: 12345,   
    name: 'Bob',
    _editing: true
};

When sending this object to the server like this:

$http({
    method: 'POST',
    url: '/save',
    data: payload
});

How can I remove the _editing property before the request is sent?

EDIT: Or any property starting with _

This filter should apply to all requests and should be able to handle deep, complex objects.

I am using Angular v1.3.18

Thank you!

Answer №1

Of course, you can utilize the $httpProvider.interceptors method for your purpose. For stripping out specific parts, a neat solution involves leveraging the functionalities of lodash:

var obj = {_f: 1, _b: 2, a: 1, b: 2 }

_.omit(obj, function (value, key) { 
  return key.indexOf('_') === 0; 
});

This code snippet will yield {a: 1, b: 2}.

On the other hand, if you prefer not to rely on an external library and stick to Angular's built-in utility functions, you can opt for:

angular.forEach(obj, function (value, key) { 
  if (key.indexOf('_') === 0) { 
    delete obj[key] 
  }
});

Answer №2

If you're looking for a solution, I suggest utilizing an http Interceptor.

All you need to do is add this line to your app.js configuration:

.config(function ($httpProvider) {
    $httpProvider.interceptors.push('httpInterceptor');
})

Next, create a factory like this:

.factory('httpInterceptor', ['$q', '$rootScope', '$filter', function ($q, $rootScope, $filter) {
    var canceller = $q.defer();
    //define some variables here
    return {

        request: function (config) {

            //Implement your modifications here
            //For example, adjust the header
            config.headers.someHeader = something;
            //Set a timeout if necessary
            config.timeout = 20000;

            return config || $q.when(config)
        },

        response: function (response) {

            //Handle the response if needed           
            return response || $q.when(response);
        },

        responseError: function (response) {

            //Handle any errors here
            return $q.reject(response);
        }
    };
}])

You now have the ability to manipulate the config object by adding or removing properties from the header or sent parameters, set timeouts, or access the response for broadcasting according to your requirements.

I trust this information proves useful.

Answer №3

Before making the POST request, it is important to remove certain properties from the payload. You can easily achieve this by using the delete method.

var payload = {
    id: 54321,
    email: 'test@example.com',
    _active: true
};

delete payload._active

$http({
    method: 'POST',
    url: '/submit',
    data: payload
});

Answer №4

Utilizing interceptors in your code can help you customize your requests and responses. As the name implies, interceptors are meant to intercept HTTP requests or responses. Quoting from the Angular documentation:

For various purposes like global error handling, authentication, or any form of pre-processing of requests or post-processing of responses, it is useful to have the ability to intercept requests before they reach the server and responses before they are delivered to the requesting code.

var app = angular.module('myApp', []);

app.config(['$httpProvider', function($httpProvider) {  
    $httpProvider.interceptors.push('myInterceptor');
}]);

app.factory('myInterceptor', ['$q', function($q) {  

    var myInterceptor = {
        request: function(config) {
            delete config.data._editing;

            return config;
        }   
    };

    return myInterceptor;
}]);

app.controller('myController', ['$http', function($http) {
    var payload = {
        id: 12345,   
        name: 'Bob',
        _editing: true
    };

    $http({
        method: 'POST',
        url: '/echo/json/',
        data: payload
    });
}]);

If you want to see this in action, I've set up a functional jsfiddle. The fiddle makes an AJAX request, so make sure to check the network tab to view the request payload.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can we utilize a loop to continuously sum up numbers until we reach a multiple of another number, let's say when the total is divisible by 4?

I am trying to create a function in JavaScript that will detect when a given number is not a multiple of 4. If the number is not a multiple of 4, I want to add numbers incrementally until it reaches the closest multiple of 4. Here’s what I have so far: ...

Tips for creating a tabbed form that easily glides between tabs

After coming across this form design, I am inspired to create something similar with a twist. Instead of having each tab display all content at once, I want the tabs to scroll from right to left, giving it a more animated effect. Can someone offer suggesti ...

Changing the close button icon in highslide popups

Utilizing highslide together with highcharts, I need to customize the functionality of the close button. Specifically, I want to trigger an additional function when a user clicks on the "X" button. Upon inspecting the "X" button, this is what appears in m ...

Aligning an object in ThreeJS to always face the camera, ensuring it is perfectly straight and flat

Reviewing this demo http://codepen.io/anon/pen/JdmMPW, I am working on creating a camera orbiting around a sphere with text labels/satellites (represented by the plane object) that should always face the camera. function render() { marker.lookAt(camera.p ...

What steps can be taken to safeguard the title of the document in the top window from being altered by any iframe or script?

My typical approach is to delete and redefine the title property like in the code snippet below: if (delete document.title) { Object.defineProperty(document, 'title', { get: getter, set: setter, enumerable: true, ...

The useEffect hook in my React app causes the homepage to refresh

Currently, I am facing a challenge in retrieving user information from the Redux state to display on the homepage after a user signs in. The issue arises when the component refreshes and all the data stored in Redux gets lost due to the useEffect hook im ...

Having trouble getting my list items to display on individual lines within the foreach loop. It just doesn't seem to be working as expected

In the event listener, I need to ensure that my list items within the forEach loop are not displaying on separate lines. This issue is causing a problem in a lengthy section of code. The goal is to update questions when an answer is clicked from a list. B ...

React Typescript: Unable to set component as element

Currently, I am working on mapping my JSX component (Functional Component) inside an object for dynamic rendering. Here's what I have devised up to this point: Interface for Object interface Mappings { EC2: { component: React.FC<{}>; ...

Why is the location search not staying centered after resizing the map on Google Maps?

I am currently working on integrating Angular with Google Maps. I need to add some markers along with location search functionality. Additionally, I am including location information in a form. When the addMarker button is clicked, a form opens and the map ...

What are the steps to implement character movement in a 2D game using JavaScript?

I'm having trouble getting the image with the ID "yoshi" to move around in my 2D game document.onkeydown = (e) => { if (e.keyCode == 37) yoshi.style.left = yoshi.offsetLeft - 5 + "px"; else if (e.keyCode == 38) yoshi.style.top = yoshi.offset ...

What are the best ways to optimize and capitalize on functionality in Electron.js?

After creating three custom buttons for the close, maximize, and minimize functions in Electron.js, I encountered an issue. While the close button is functioning properly, I am struggling with implementing the maximize and minimize buttons. In fact, I have ...

It appears that the jQuery.post() method is being overlooked or bypassed for unknown reasons

Trying to understand why the call to jQuery.post() isn't fetching the data or running the function after the fetch. Three files are included: an HTML file, a JavaScript file, and a PHP file. The HTML contains the modal element intended to appear when ...

Utilizing React with an alternative server-side language

I have a small PHP backend for my website and I want to incorporate React on the front end. However, being new to front-end development and React, I am finding this process confusing as most online examples assume a JavaScript backend with Node modules. W ...

The Appsheet algorithm determined the exact expiration date as 2 days from the specified date

In my Appsheet, I have two columns: Production Date and Expired Date. If the Production Date is 35 months before the Expired Date, how can I create a formula in Appsheet to calculate this? For example, if the Production Date is 01/10/2023, then the Expired ...

Maximizing JavaScript DOM efficiency

In my code, I have numerous elements that need to be hidden and displayed dynamically. To facilitate this, I plan on utilizing the document.getElementById('x').style.display method. However, instead of directly using this method each time, I have ...

Attempting to implement a smooth fade effect on my image carousel using React-Native

Struggling to animate this image carousel in reactNative and feeling lost. Despite reading the documentation on animations, I can't figure out how to implement it properly. My attempts keep resulting in errors. Any assistance would be greatly apprecia ...

What is the best way to update a deeply nested array of objects?

I have an array of objects with nested data that includes product, task, instrument details, and assets. I am attempting to locate a specific instrument by supplier ID and modify its asset values based on a given number. const data = [ { // Data for ...

Verify the identity of all REST API requests without the need for a username or password in order to obtain a

I have a unique setup where I am selling products. The API fetches product data from a centralized node back-end and displays it on an angular front-end that is hosted on multiple domains. The challenge I'm facing is the need to authenticate all reque ...

Error 16 occurred when attempting to ngUpgrade two different versions of Highcharts

After successfully upgrading my app to use ngUpgrade, I encountered an issue while trying to incorporate Highcharts. In the original version of the app, there was an older version of Highcharts designed for AngularJS. However, in the new hybrid app using ...

The image fails to appear while creating a PDF in AngularJS using pdfmake

I recently started using a fantastic pdf printing library called pdfmake in my angularjs SPA to generate PDF files. Everything was going smoothly until I tried to include images in the PDF. Strangely, when I added images, nothing happened - no errors, no e ...