2017-01-30 66 views
1

我有一个命名为machineForm指令,它有一个dataService并行GET请求 - 角JS

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

我连续两次调用该指令。

<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> 

dataServicegetMachineTaxesById是在这里:

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

如果我评论的<machine-form>中的任何一个,但不是当两者都称为同时它工作正常。我得到一个response{"message":"Authorization has been denied for this request."}

是否与发送并行请求一次做什么?我应该在发送其他请求之前等待一个请求完成。

注意:我为每个请求使用访问令牌。

+0

看着你的浏览器的*网络*控制台。找到失败的请求并检查“授权”请求标头。它是否适当设置?这些cookie值何时设置('token_type'和'access_token')? – Phil

+1

从安全角度来看,执行多个并发请求没有问题 - 您的端点是否限制特定令牌的并发连接,或者可能是令牌单独使用? – Brian

+0

@Brian还有其他的请求是成功的。只有当我尝试多次访问相同的API网址时,它会以'{“message”:“作为响应。”}此请求的授权已被拒绝。“} –

回答

3

为了让服务执行XHR时顺序,保存从以前的呼叫,并从链它的承诺:

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