Concurrent HTTP Requests - AngularJS

My directive, known as machineForm, includes a dataService:

dataService.getMachineTaxesById($scope.machineId).then(function (response) {
     $scope.machine.machineTaxes = response.data;
});

I am using this directive twice simultaneously.

<div class="modal-compare-item">
    <machine-form app-data="appData" 
        index="analyzie_index" 
        machine-id="machineAnalyze.id" 
        machine="machineAnalyze" 
        action="'edit'">
    </machine-form>
</div>
<div class="modal-compare-item">
    <machine-form app-data="appData" 
        index="compare_index" 
        machine-id="machineCompare.id" 
        machine="machineCompare" 
        action="'edit'">
    </machine-form>
</div>

The dataService function for getMachineTaxesById is shown below:

// Get Machine Taxes By Id
 this.getMachineTaxesById = function(machine_id) {         
     return $http({
         method: 'GET',
         url: 'https:xyz/api/MachineTaxes/Machine/'+ machine_id,
         headers: {
             'Accept': 'application/json',
             'Content-Type': 'application/json',
             'Authorization' : $cookies.get('token_type') + " " + $cookies.get('access_token')
         }
     });
 };

If I comment out one of the <machine-form> instances, everything works fine. However, when both are called concurrently, I receive this error message in the response:

{"message":"Authorization has been denied for this request."}

Could this issue be related to sending parallel requests? Should I wait for one request to finish before sending the other?

Note: An access token is used for each request.

Answer №1

If you want the service to run XHR requests one after another, you can achieve this by storing the promise from the previous call and chaining the next call to it:

app.service("dataService", function($http) {
    var lastRequestPromise;
    
    // Retrieve Machine Taxes By Id
    this.getMachineTaxesById = function(machine_id) {
        var config = {
            method: 'GET',
            url: 'https:xyz/api/MachineTaxes/Machine/' + machine_id,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Authorization': $cookies.get('token_type') + " " + $cookies.get('access_token')
            }
        };
        
        if (!lastRequestPromise) {         
            lastRequestPromise = $http(config);
        } else {
            lastRequestPromise = lastRequestPromise.catch(function (errorResponse) {
                // Convert rejected promise to success
                return errorResponse;
            }).then(function(response) {
                // Return httpPromise for chaining
                return $http(config);
            });
        }
        
        return lastRequestPromise; 
    };
});

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

No results returned by Mongoose/MongoDB GeoJSON query

I have a Schema (Tour) which includes a GeoJSON Point type property called location. location: { type: { type: String, enum: ['Point'], required: true }, coordinates: { type: [Number], required: true ...

Website search bar - easily find what you're looking for

I've tested this code and it works well on the basintap page. However, I'm interested to find out how I can search for something when I'm on a different page instead? <?php $query = $_GET['query']; $min_length = 2; if(strlen($ ...

The fixed position setting does not anchor the elements to the bottom of a container

When applying the following styles: #fullpage-menu > .gradient { position: fixed; bottom: 0; left: 0; width: 100%; height: 0.3rem; } To the element with ID #fullpage-menu, which is styled as follows: #fullpage-menu { height: 100 ...

Looking for the location of cli.js in Protractor 5.0 and wondering how to configure Protractor in Eclipse?

I'm currently searching for the cli.js file in Protractor, but I can't seem to locate it in the lib folder. Instead, I found a cli.js file under built (node_modules/protractor/built). Is this the correct file to use for setting up Protractor in E ...

Consolidate all data connected to the specified key from a JSON dataset

Looking at the json string presented below [{"_id":"9/17/2015","amt1":0,"amt2":13276.5},{"_id":"9/18/2015","amt1":8075,"amt2":6445.5}] The expected outcome is: [{"_id": ["9/17/2015", "9/18/2015"], "amt1": [0, 8075], "amt2": [13276.5, 6445.5]}] Is there ...

Tips for utilizing navigator.getDisplayMedia with automatic screen selection:

navigator.mediaDevices.getDisplayMedia({ audio: false, video: true }).then(gotMedia).catch(function(e) { console.log('getDisplayMedia() error: ', e); }); Triggering the above code will result in a popup like this. There is anoth ...

Is JavaScript not having an impact on your HTML code?

I am attempting to create a dynamic number change when the user interacts with the "range-slider" element, but the number is not updating as expected. Below is the code I have written: var rangeSlider = function() { var slider = $(".range-slider"), ...

Is it possible for me to reconstruct the "reducer" each time the useReducer hook is rendered?

Here is an example taken from: https://reactjs.org/docs/hooks-reference.html#usereducer const initialState = {count: 0}; function reducer(state, action) { switch (action.type) { case 'increment': return {count: state.count + 1}; ...

Exploring the implementation of constructors and classes in JavaScript

I have a task to create a class named ShoppingCart with specific instructions: The class should have a constructor that initializes the total attribute to zero and creates an empty dictionary attribute called items. There should be a method named add_ite ...

Verify ngRoute route validity

In my application, I am utilizing angular-route to handle routing. While creating some links, I want to verify if the link is defined in routeProvider to prevent it from redirecting to the 404 page. Is there a method within ngRoute that allows me to conf ...

How can I apply various textures in three.js?

Hello there! I'm diving into the world of threejs and currently working on a block game similar to Minecraft. Instead of relying solely on objects, I've decided to build my program using planes (specifically the PlaneGeometry class). As I wrap ...

The alignment issue persists when attempting to set 'relative' on the parent and 'absolute' on the inner element in a Bootstrap column for bottom alignment

Here is a snippet of my basic HTML code: <div class = "row"> <div class = "col-xs-8"> <p>long long long long text that generates a taller column</p> </div> <div class = "col-xs-4"> <p> ...

The Resharper guideline "Function Parameter" doesn't allow the usage of AngularJS service names

I have a question regarding naming conventions in my AngularJS app. Currently, all my service names start with an uppercase character. However, I am facing an issue where service parameters must match the service name, but Resharper's JavaScript "Func ...

The GET request endpoint is not being reached within the Angular application

My goal is to set up a persistent login feature for an Angular application, where I can navigate to different pages or refresh without getting logged out. Upon inspecting the debugger, it seems that my /api/users route is not being accessed. The /api/sess ...

Deploying an Angular 2 application using SystemJS and Gulp can sometimes feel cumbersome due to its

Although I have experience developing with Angular, I recently started working with Angular 2. After completing the quickstarter tutorial, I attempted to deploy the finished application on a server in production mode. My lack of experience with SystemJS a ...

Hide all the div elements on the web page and only display one when a button is clicked

I have successfully set up a few buttons that can show and hide divs on click. However, I am wondering if it is possible to hide all other divs when one is showing, and also have "divone" show up on load. Buttons: <button class="btn btn-outline-primar ...

Enhancing the readability of modals with Angular Dialog Service

I have been utilizing the Angular Dialog Service to create popup forms on my website. The source code for this service can be accessed here: https://github.com/m-e-conroy/angular-dialog-service/blob/master/README.md However, I am experiencing an issue wit ...

Converting information from a model into individual variables

I'm a newcomer to typescript and angular, and I've been attempting to retrieve data from firebase using angularfire2. I want to assign this data to variables for use in other functions later on. I am accustomed to accessing object members using d ...

Is file timestamp utilized by Apache to verify if a resource has been changed?

Currently, I am working on an HTML page that references a large JavaScript file (1MB+) that is rarely updated. According to this source, the JavaScript file will not be resent if it hasn't been modified. I'm curious about how Apache determines i ...

Error encountered: Multer does not recognize the field when attempting to upload multiple files in a node.js environment

I would like to upload two files in one request using Node.js and I am utilizing multer for this task. Here is my request in Postman: https://i.sstatic.net/8ZEno.png Additionally, I am using multer in routing: router.post( "/Create", Uploa ...