2014-02-25 66 views

回答

3

我知道這是一個遲到的答案,但我創建了一個角度模塊來啓用HTTP批量請求。該模塊在這裏https://github.com/jonsamwell/angular-http-batcher,我在這裏寫了一篇關於它的博客文章http://jonsamwell.com/batching-http-requests-in-angular/

該模塊對開發者來說是透明的,所以一旦你包含了它並設置了一個批處理端點,所有對該服務的調用都將自動進行批處理。讓我知道你是否需要任何幫助開始使用它。

例如,下面的3個http請求將自動分批生成一個請求!

var app = angular.module('httpBatchExample', ['jcs.angular-http-batch']); 

app.config([ 
    'httpBatchConfigProvider', 
    function (httpBatchConfigProvider) { 
     // setup some configuration to tell the module that requests to 
     // 'https://api.myapp.com' can be batched and send the batch request to https://api.myapp.com/batch 
     httpBatchConfigProvider.setAllowedBatchEndpoint(
      'https://api.myapp.com', 
      'https://api.myapp.com/batch'); 
    } 
]); 

app.controller('mainCtrl', [ 
    '$scope', 
    '$http', 
    function ($scope, $http) { 
     // Get the data as normal which will automatically be turned into a single HTTP request 
     $http.get('https://api.myapp.com/products').then(function (data) { 
      console.log('success 0 - ' + data.data); 
     }, function (err) { 
      console.log('error 0 - ' + err); 
     }); 

     $http.get('https://api.myapp.com/products/2').then(function (data) { 
      console.log('success 1 - ' + data.data); 
     }, function (err) { 
      console.log('error 1 - ' + err); 
     }); 

     $http.put('https://api.myapp.com/products', { 
      Name: 'Product X', 
      StockQuantity: 300 
     }).then(function (data) { 
      console.log('success 2 - ' + data.data); 
     }, function (err) { 
      console.log('error 2 - ' + angular.fromJson(err)); 
     }); 
    }]);