2017-01-30 95 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;  
    }; 
});