2015-07-16 2 views
0

Я хочу изменить запрос этой пирамиды на обещания с помощью $ q.

app.controller('Ctrl', function ($scope, $http, $q) { 

$http.post('http://localhost:1235',data_post1).success(function (data){ 
    console.log("1"); 
    $http.post('http://localhost:1236',data_post2).success(function (data){ 
     console.log("2"); 
     $http.post('http://localhost:1237',data_post3).success(function (data){ 
      console.log("3"); 
      $http.post('http://localhost:1238',data_post4).success(function (data){ 
       console.log("4"); 
      }); 
     });  
    }); 
}); 

} 

Я никогда не использовал $ q раньше.

+0

'. тогда 'обещание цепочки было бы лучше здесь, а не использовать' $ q' обещание здесь –

ответ

1

так лучшая практика будет тянуть запросов HTTP из контроллера

так что если у вас есть завод, как

app.factory("fooSrvc", ["$q", "$http", function($q, $http){ 
    return { 
     data1: function(postData){ 
      var deferred = $q.defer(); 
      $http.post("", postData).success(function(results){ 
       deferred.resolve(results); 
      }); 

      return deferred.promise; 
     }, 
     data2: function(postData){ 
      var deferred = $q.defer(); 
      $http.post("", postData).success(function(results){ 
       deferred.resolve(results); 
      }); 

      return deferred.promise; 
     } 
    }; 
}]); 

тогда ваш контроллер может выглядеть

app.controller("Ctrl", ["$scope", "fooSrvc", function($scope, fooSrvc){ 
    fooSrvc.data1(dataTopost).then(function(results){ 
     // do something with it here possibly 
     fooSrvc.data2(moreDataToPost).then(function(moreResults){ 
      // do something with it here possibly 
     }); 
    }); 
}]); 
+0

Спасибо. Я проверю. –

Смежные вопросы