Exploring Angular Resource: Optimizing and shaping data in requests and responses

In my angular + closure project, I'm looking to selectively transform / intercept requests without affecting all of them in order to convert camelCase keys to snake_case.

While I successfully added default interceptors and transformers through $httpProvider in my config, it impacted all requests, including templates. I explored adding an option to each Resource config to control the transforms but this option was only accessible in requests, not responses, leading to the need to check if it's JSON first which is less than ideal.

I also encountered challenges where the interceptor for $resource restricts to response and responseError interceptors, making it frustrating to work with.

My goal is to find a way to intercept each request/response JSON object and keep the transformers organized in their own file/class/factory while allowing flexibility on when to use them.

What would be the most effective approach to achieve this?

Answer №1

Incorporating an $http interceptor can enhance your application's functionality. The $resource tool utilizes the $http service in the backend for sending requests, so this modification will have a broad impact.

function CustomInterceptor() {
    return {
        request: config => {
            // Implement custom logic here
            // Use if statements to selectively modify endpoints
        }
    }
}

function setConfig($httpProvider) {
    $httpProvider.interceptors.push('CustomInterceptor');
}

angular
    .module('app')
    .factory('CustomInterceptor', CustomInterceptor)
    .config(setConfig);

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

Create a dynamic slideshow using a bootstrap carousel in conjunction with the powerful php glob() function

I'm struggling to create a homepage featuring a slider that pulls images dynamically from a subfolder within the Wordpress uploads directory. Here's my code: <div id="" class="carousel slide" data-ride="carousel"> <!-- Wrapper for sl ...

Mastering the art of iterating through arrays using node.js request()

After transitioning from passing single values to multiple values in my node API, I encountered an issue where the API no longer responded. Here is an example of single values for fields: tracking: "123", // Only one tracking number carrier: "usps" // On ...

I am unable to access my JavaScript class in Laravel Mix

Within my Laravel project, I have developed a custom form validation class. However, after running npm run dev, I am unable to access this class. Files: small-form-validation.js class SmallFormValidator { errMsgs = { required: 'This fiel ...

React JS's popup feature can be unreliable, as it tends to break the application frequently

I have been developing a web application that interacts with a public API and presents the retrieved data in a table format. However, I am encountering an issue where clicking the "Click to Display Hottest Planet" button sometimes results in an error. How ...

"Implementation of a dropdown menu featuring deletion capabilities within an ng-repeat loop

Is there a way to instantly reflect the view after deleting a tag on click? Currently, the change is only visible after refreshing. <div class="dropdown"> <span ng-repeat="tag in tag track by $index" data-toggle="dropdown">[[t ...

The note-taking app's JavaScript code does not currently have the capability to store notes in local storage

const noteContainer = document.querySelector(".note-container"); const createBtn = document.querySelector(".btn"); let notes = document.querySelectorAll(".input-box"); function showNotes() { noteContainer.innerHTML = localS ...

Discovering how to create a line break within a text area using the $scope feature in Angular

I'm looking to incorporate a text area for chat input that is resizable. I would like to have some pre-filled texts in it, such as: Hi Jhon, Thanks for contacting us.... I want the text to appear on a new line after the existing content in the textar ...

How can I create a button that prints the page content and then sends it to the backend using JavaScript for submission?

Is there a way to print content from a page and then submit form data to make changes to a backed database using just one button? I've attempted to include the print action within an on-click function, but it does not submit the form after printing. ...

Utilizing MeshPhongMaterial in THREE.js for Particle Material with Size Adjustment

My goal is to create particles that exhibit the characteristics of a Phong material, which means they react to light. I have been using the "createMultiMaterialObject" method to achieve this, and it has worked well for the most part. However, I have encoun ...

Error message "Unable to load / invalid sound with zero-length duration reported on Chrome and Firefox."

Encountered an issue where / invalid sound zero-length duration was reported in Chrome and Firefox. However, the error only appeared in IE10. Here is the code snippet: foo = soundManager.createSound({ id: 'bar', url: '../music/ ...

"Failure to manipulate the style of an HTML element using Vue's

<vs-tr :key="i" v-for="(daydatasT, i) in daydatas"> <vs-td>{{ daydatasT.Machinecd }}</vs-td> <vs-td>{{ daydatasT.Checkdt }}</vs-td> <vs-td>{{ daydatasT.CheckItemnm }}< ...

What is the best way to draw a rectangle outline in Vue.js without the need for any additional packages?

I have been attempting to craft a rectangle outline using vueJS, but so far I have not had much success. I am hoping to achieve this using only CSS, but despite my efforts, I have not been able to find a solution. My goal is to create something similar to ...

Exploring the World of Browserify Submodules

/xyz /abc.js /abcdef.js /index.js When working with node.js, if you use the require statement for a directory (require('xyz')), it will automatically search for an index.js file within that directory and return the exports defined in that ...

Rendering a Component Inside Another Component

I am facing a situation where I have a component named TicketView being used within another component called Table. The initialization of TicketView in the table looks like this: <TableRow key={index}> ... <TableRowColumn style={{width: & ...

Converting dates in JavaScript to the format (d MMMMM yyyy HH:mm am) without using moment.js

Looking to convert the date "2020-02-07T16:13:38.22" to the format "d MMMMM yyyy HH:mm a" without relying on moment.js. Here is one method being utilized: const options = { day: "numeric", month: "long", year: "numeric", } var date1 = new Date ...

Dropdown Menu with Bootstrap 4 Toggle Checkbox

Within a Bootstrap 4 dropdown menu, I integrated a checkbox styled with the Bootstrap Toggle Plugin. However, upon clicking the toggle switch, the menu abruptly closes. To address this issue, I added onclick="event.stopPropagation();" to the menu item, as ...

Issue with Vue property's sub-object not inheriting methods from prototype

Incorporating Vue into my project to showcase an intricate hexagonal grid has been quite challenging. Utilizing the Honeycomb library for handling the grid data in memory has proven to be both beneficial and complex. The library introduces a specialized Gr ...

Using AJAX and PHP to dynamically fill HTML drop-down menus

In order to populate the DropDown controls on my HTML Form dynamically, I have implemented a code that utilizes AJAX to make a call to a .php file. This .php file is responsible for filling the DropDown control with values from a single column. Throughout ...

rails/jquery/ajax: The completion function is not being triggered

My code was functioning correctly without any errors when making an AJAX call that didn't require a return value. In my Javascript (specifically coffeescript), I had the following: $.ajax({ url: "/images/" + image_id + "/" + action, type ...

Create genuinely private methods within an ES6 Module/Class specifically for use in a nodejs-exclusive environment, ensuring that no data is exposed

Although there are no true private methods within ES6 classes, I stumbled upon something interesting while experimenting... While it's not possible to completely hide object properties, I attempted to follow OOP principles by dividing my classes into ...