1

For example, I have a controller to show user a list view, some columns need data comes from another endpoint, so I wrote these with intuition, could you tell me how do I re-factory them?

$http.get($scope.urlA)
  .success(function(res){
    $scope.dataA = res.data;

    $http.get($scope.urlB)
      .success(function(res){
        $scope.dataB = res.data;
      })
      .error(function(err){
        if (err) throw err;
      });
  })
  .error(function(err){
    if (err) throw err;
  });
2
  • does $http.get($scope.urlB) require anything in $http.get($scope.urlA)? Commented Aug 1, 2014 at 5:25
  • @ryeballar Sorry for that missing, the answer is YES. Commented Aug 1, 2014 at 5:40

2 Answers 2

2

Then best practice would be two create two factory methods for the two $http.get calls. In Angular $http invoke promises by itself so your factory will look like:

myapp.factory('getHttpData',function($http){
    return{
        getURLA:function(){
            return $http.get('/urlA');
        },
        getURLA:function(){
            return $http.post('/urlB');
        }
    }
});

Then in Controller you can invoke both the factory functions like this:

  .controller('testCtrl',['getHttpData',function(getHttpData){
       getHttpData.getURLA().then(function(data){
              //do whatever you want
              getHttpData.getURLB().then(function(Bdata){
                 //do whatever you desire
              }):
       });
  });
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, I think your solution is exactly what I need.
0

It doesn't look like the second call depends on the first so you can just call them separately:

$scope.data = {};

$http.get('http://example/url/a')
    .success(function(data) {
        $scope.data.a = data;
    });

$http.get('http://example/url/b')
    .success(funciton(data)) {
        $scope.data.b = data;
    });

If call b depends on data from call a then call service b from call a's success callback.

2 Comments

So what will happen if I had 5 $http requests which nested depended?
If you have 5 calls where each successive call depends on the previous then you have to chain the promises returned on the calls so they can be sequential, which is effectively what you are doing in your example code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.