Monitoring the flow of data between Angular JS resources and the promise responses

In my application, there is a grid consisting of cells where users can drag and drop images. Whenever an image is dropped onto a cell, a $resource action call is triggered to update the app.

My goal is to display a loader in each cell while the update call is in progress. For example, when a user drops an item, a spinning loader should appear in the cell. Once the call completes, the loader should be removed and the cell updated accordingly.

All cells trigger the same call with different data being passed. The challenge I'm facing is how to identify which cell the response corresponds to, especially when multiple cells are loading simultaneously. Ideally, the API response should contain information about the cell location, allowing JavaScript to remove the loader and update the correct cell.

However, if the call fails for any reason, it becomes tricky to determine which cell had the failed call. How can the app identify the specific cell that needs the loader removed in case of a failed call?

I am looking for a solution where data specified in the $resource call can be accessed in the promise response. For instance:


rest = $resource('www.api-source.com/layout/34/cells','post',{cell_location:'2x4'},{'post': {method:'GET', isArray: false}});
rest.setTracker('2x5');
rest.post( );     

rest.$promise.then(function(data) {
    $scope.removeLoader(data.cell_data.location);
},function(data, status, headers, config) {
   cell = rest.getTracker( );
   $scope.removeLoader(cell);
}

This approach involves setting a value in the $resource object and extracting it from the promise. While this may not be the most optimal method, it aims to ensure that the loader is removed even if the cell location data is missing.

Answer №1

After some careful examination, I recently discovered the solution to my issue by utilizing the $promise.finally( ) callback function. This handy feature allowed me to extract the necessary data and successfully clear the loader, even in cases where the call did not bring the expected results.

selectedCell = '3x5';
requestData = $resource('www.api-source.com/layout/56/cells','post',{location:selectedCell},{'post': {method:'GET', isArray: false}}).post( );     

requestData.$promise.then(function(response) {
    $scope.hideLoader(selectedCell);
},function(response, status, headers, config) {
   $scope.displayErrorMessage('Error');       
}).finally(function(){
   $scope.hideLoader(selectedCell); 
});

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

Does it follow standard practice for Array.filter to have the capability to also perform mapping on an array of objects?

While experimenting with Array.filter, I made an interesting discovery. By forgetting to include an equality check, my array was unexpectedly mapped instead of filtered. Here is the code snippet that led to this result: const x = [{ name: 'user' ...

Create a regular expression that permits a sequence of numbers (either integer or decimal) arranged in groups of up to five, with each

Is it possible to create a regular expression that allows integers and decimals? var reg = /^((\s*)|([0-9]\d{0,9}(\.\d{1,3})?%?$))$/.; How can users input 0 to 5 groups of integers and decimals separated by |? Updated: This regex sh ...

Ways to recover HTML elements that have been eliminated by jQuery's remove

$(document).ready(function() { $('#remove').click(function() { $('.test').remove(); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="test-wra ...

Using jQuery to create dynamic elements that fade out with timers

My website has a simple message system that displays messages in a floating div at the top of the page. Each message is supposed to fade out after a certain amount of time, but I want users to be able to pause the fading process by hovering over the messag ...

The function Router.use is looking for a middleware function, but instead received an object in node.js /

I encountered an issue while trying to setup routing in my application. Whenever I attempt to initialize a route using app.use() from my routes directory, I receive an error stating that Router.use() requires a middleware function but received an Object in ...

What is the best way to retrieve a return string from an external program using XPCOM in Firefox?

Is there a way to execute an external program in XPCOM and retrieve the actual return string from it, instead of just the return code? I have researched nsICommandLine, nsICommandLineHandler, nsICommandLineRunner, and nsIProcess but it seems like none of ...

Accessing iframe's HTML using a server-side solution by circumventing the Cross-Domain Policy

Our current challenge involves accessing dynamically generated HTML elements using JavaScript, particularly when trying to extract image URLs from these elements. When the HTML elements are generated solely through JavaScript, extracting the URL is straigh ...

Postman is displaying [object object] as the return value, but the actual value is not

Currently, I am working on automating tasks using Postman One interesting aspect is the presence of a vehicles array in the body { "Vehicles":[ { "car":"{{car}}", "bike":"{{bike}}&quo ...

Malfunction in parsing the post request body

Recently, I have been facing an issue while attempting to execute a $http.post request in this manner: $http({ method: 'POST', url: '//192.168.2.1:3000/auth/signup', data: $scope.credentials, headers: { 'Content- ...

Verify whether a specific value exists in my React array; if it does, display a specific component

I need to display different components based on the following criteria: Whether the items contain a specific value And if all 10 items have that value const DisplayComponents = ({ data }: Props) => { const filteredItems = data.items?.filter( ( ...

Is there a way to obtain an array after subscribing to an RxJS method?

I am struggling with the following code snippet: Rx.Observable.from([1,2,3,4,5,6]) .subscribe(x=>console.log(x)); Is there a way to modify this code so that instead of iterating through the array elements from the .from() method, I can return the enti ...

Using JavaScript and HTML, create a click event that triggers a drop-down text

Can anyone help me with creating a dropdown feature using JavaScript, HTML, and CSS? I want to be able to click on the name of a project and have information about that project show up. Any suggestions on how I can achieve this? Thanks in advance! ...

Unwrapping React: Mastering the Art of Prop Extraction and Sharing

Imagine I have 2 input elements below, both with the same props except for the className <ReactCardFlip> <input type="text" maxLength={1} className={inputStyles.input} defaultValue={value} ...

Loading a gallery dynamically using AJAX in a CakePHP application

I am currently working with Cakephp 2.8.0 and I am facing an issue with implementing ajax in my application. I have a list of categories displayed as li links, and upon clicking on a category, I need to remove certain html code, locate the necessary catego ...

Utilizing a Json.Net object within an Ajax request

Is there a way to pass a .Net object in an Ajax call using the Json.Net javascript library instead of json2.js? You can find more information on passing complex types via Ajax calls at this link: I am familiar with how to serialize and deserialize object ...

Customize CKEditor by automatically changing the font family when the page is loaded

How can I change the font-family of CKEditor to Meiryo based on a JavaScript boolean? I attempted this code in my custom JS within an if condition, but it did not successfully change the font-family: config.font_style = { element : 'span&apo ...

Utilizing a segment of one interface within another interface is the most effective method

In my current project using nextjs and typescript, I have defined two interfaces as shown below: export interface IAccordion { accordionItems: { id: string | number; title: string | React.ReactElement; content: string | React. ...

Determine the HTTP request method when capturing AJAX responses

As I take control of all AJAX responses on a global scale, I find myself searching for an elegant solution to identify the method (such as POST/PUT/GET) that was initially used to make the request triggering the intercepted response. Below is my approach ...

How can we call a function in HTML from an external JavaScript file?

I am attempting to utilize a function that I have defined in my .js file within my HTML document. js/newsalerts.js function decodeHTML(html) { //https://stackoverflow.com/a/2989105/4650297 var tempDiv = document.createElement("DIV"); tempDiv. ...

Serialize a form while keeping the submitted data private

Is there a way to achieve serialization without triggering the submit function for an ajax call? I've searched extensively for a solution to this issue without any luck. The java script function is invoked when a button within the form is clicked. do ...