2016-04-22 70 views
-1

我是AngularJS中的新成员。在我的项目中,我将按时调用多个$ http请求。但是,在$ http请求之前成功的数据是下一个$ http请求中的一个参数。

我试试这个:

$http.post(URL1, params1).success(function(data){ 
    $http.post(URL2, data.result).success(function(){ 
      ...... 
    }) 
}).error(function(err){}) 

但它使复杂和难以处理。如何解决它?谢谢。

+0

这是不平行。这些是嵌套顺序调用。 – skubski

+0

谢谢,我将编辑我的问题标题:) –

+0

使用'.success'已折旧,您应该坚持使用'.then' – webduvet

回答

0

这是可以做到像这样

var FlightDashboard = function($scope, user, travelService, weatherService) 
    { 
     // Level 1 
# 
     travelService 
      .getDeparture(user.email)     // Request #1 
      .then(function(departure)    // Response Handler #1 
      { 
       $scope.departure = departure; 
# 
       // Level 2 
# 
       travelService 
        .getFlight(departure.flightID)  // Request #2 
        .then(function(flight )    // Response Handler #2 
        { 
         $scope.flight = flight; 
# 
         // Level 3 
# 
         weatherService 
          .getForecast(departure.date)  // Request #3 
          .then(function(weather)   // Response Handler #3 
          { 
           $scope.weather = weather; 
          }); 
        }); 
      }); 
    }; 
1

这是非常简单的控制异步操作​​async module或者你可以使用vasync这就好比异步但具有更好的日志记录的例子。

var postSomething1 = function(cb) { 
    $http.post(URL1, params1).success(function(data){ 
     cb(null, data); 
    }) 
    .error(cb); 
}; 
var putSomething = function(cb) { 
    $http.put(URL1, params1).success(function(data){ 
     cb(null, data); 
    }) 
    .error(cb); 
}; 

var tasks = [ 
    postSomething, 
    putSomething 
]; 
var done = function(err, result){ 
    console.log("Complete with err", err, " result", result); 
}; 

async.parallel(tasks, done); 

因为你有更多的方法,你意识到你可以重构这样的:

var call = function(method, url, params) { 
    return function(cb) { 
     var method = method.toLowerCase(); 
     $http[method](url, params).success(function(data){ 
      cb(null, data); 
     }) 
     .error(cb); 
    }; 
}; 
var tasks = [ 
    call('POST', 'http://example.com/create/event', { event_name: 'Cool' }), 
    call('PUT', 'http://example.com/update', { name: 'Jon' }), 
    call('PUT', 'http://example.com/event/enable', { enable: true }), 
    call('GET', 'http://example.com/list/34') 
    ... 
]; 
var done = function(err, result){ 
    console.log("Complete with err", err, " result", result); 
}; 

async.parallel(tasks, done);