Deepak Bandi
Deepak Bandi

Reputation: 1904

Parallel Get Requests - Angular JS

I'm having a directive named as machineForm which has a dataService

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

I'm calling this directive twice at a time.

<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 for getMachineTaxesById is here:

// 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')
         }
     });
 };

It works fine if i comment any one of the <machine-form> but not when both are called at a time. I get a response saying {"message":"Authorization has been denied for this request."}

Is it anything to do with sending parallel request at a time? Should I wait for one request to complete before sending other.

Note : I'm using access token for each request.

Upvotes: 1

Views: 271

Answers (1)

georgeawg
georgeawg

Reputation: 48968

To have the service execute the XHRs sequentially, save the promise from the previous call and chain from it:

 app.service("dataService", function($http) {
     var lastPromise;
     // Get 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 (!lastPromise) {         
             lastPromise = $http(config);
         } else {
             lastPromise = lastPromise.catch(function (errorResponse) {
                 //convert rejected promise to success
                 return errorResponse;
             }).then(function(response) {
                 //return httpPromise to chain
                 return $http(config);
             });
         };
         return lastPromise;    
     };
 });

Upvotes: 3

Related Questions