0

This should be easy but I cant seem to get it to work. I have the below code which are basically fetching data using $http.

FYI I'm using POST and not GET.

Right now they run in parallel. One might finish before the other. My goal is to present the data once all have finished. So I read up on $q but I cant seem to get it to work.

    $scope.getRestOpen = function () {
    $http({
        method: 'post',
        url: "http://www.xxx.co.uk/php/xxx/restopen-get.php",
        data: $.param({ 'location' : $scope.l, 
                       'time' : $scope.t,
                       'day' : $scope.d,
                       'type' : 'get_restopen' }),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).then(function successCallback(response) {
        // this callback will be called asynchronously
        // when the response is available
        $scope.open = response.data.data;
    }, function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        $scope.open = [];
    });
}

$scope.getRestClosed = function () {
    $http({
        method: 'post',
        url: "http://www.xxx.co.uk/php/xxx/restclosed-get.php",
        data: $.param({ 'location' : $scope.l, 
                       'time' : $scope.t,
                       'day' : $scope.d,
                       'type' : 'get_restclosed' }),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).then(function successCallback(response) {
        // this callback will be called asynchronously
        // when the response is available
        $scope.closed = response.data.data;
    }, function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        $scope.closed = [];
    });
}

As you can see I can get the returned data from my $http calls in the main function itself; $scope.closed = response.data.data; and $scope.open = response.data.data;

But I don't want to assign them to the $scope just yet until both have completed. So I should be able to use $q to do the below but I don't get data in my $scope and no errors.

$q.all([$scope.getRestOpen, $scope.getRestClosed]).then(function(data){
    $scope.open = data[0].data; // doesn't work
    $scope.closed = data[1].data // doesn't work
});

Am I doing something wrong?

3
  • jsfiddle.net/ThomasBurleson/QqKuk Commented Nov 28, 2015 at 19:33
  • No idea how to change all my code to work like that. There's nothing wrong with my 2 functions. Just need guidance on how to incorporate $q Commented Nov 28, 2015 at 19:45
  • its returning the promise to a scope value Commented Nov 28, 2015 at 19:46

3 Answers 3

2

You need to have each item in your $q.all() array returning a promise. Because nothing is returned, your response is going to be [undefined, undefined].

All you need to do is replace $scope.open = response.data.data; with return response.data.data; and it should work. Make sure to do the same thing in the catch block.

EDIT: Here is how the code should look

$scope.getRestOpen = function () {
    return $http({
        method: 'post',
        url: "http://www.xxx.co.uk/php/xxx/restopen-get.php",
        data: $.param({ 'location' : $scope.l,
                'time' : $scope.t,
                'day' : $scope.d,
                'type' : 'get_restopen' }),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).then(function successCallback(response) {
        // this callback will be called asynchronously
        // when the response is available
        return response.data.data;
    }, function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        return [];
    });
}

$scope.getRestClosed = function () {
    return $http({
        method: 'post',
        url: "http://www.xxx.co.uk/php/xxx/restclosed-get.php",
        data: $.param({ 'location' : $scope.l,
                'time' : $scope.t,
                'day' : $scope.d,
                'type' : 'get_restclosed' }),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).then(function successCallback(response) {
        // this callback will be called asynchronously
        // when the response is available
        return response.data.data;
    }, function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        return [];
    });
}
Sign up to request clarification or add additional context in comments.

2 Comments

Any chance you can modify my code to implement this
@moh.ABK Edited my response to include how the code should look
0

Modify your code like this

 $scope.getRestOpen = function () {
    return  $http({
       method: 'post',
       url: "http://www.xxx.co.uk/php/xxx/restopen-get.php",
       data: $.param({ 'location' : $scope.l, 
                   'time' : $scope.t,
                   'day' : $scope.d,
                   'type' : 'get_restopen' }),
      headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    });
 }

 $scope.getRestClosed = function () {
    return $http({
      method: 'post',
      url: "http://www.xxx.co.uk/php/xxx/restclosed-get.php",
      data: $.param({ 'location' : $scope.l, 
                   'time' : $scope.t,
                   'day' : $scope.d,
                   'type' : 'get_restclosed' }),
      headers: {'Content-Type': 'application/x-www-form-urlencoded'}
  });
 }

 $q.all([$scope.getRestOpen(), $scope.getRestClosed()]).then(function(data){
   $scope.open = data[0].data; 
   $scope.closed = data[1].data;
 });

1 Comment

Remember to call both functions: $scope.getRestOpen().
0

Look this example and read comment in code:

var myApp = angular.module('myApp', []);

function MyCtrl($scope, $q, $timeout) {
    
    var thenFn = function(value) {
        console.log('resolved ', value);
        return value;
    },
    
    q1 = $scope.q1 = $q.defer(),
    q2 = $scope.q2 = $q.defer(),
    p1 = $scope.q1.promise,
    p2 = $scope.q2.promise;
    
    //Wait complete all request 
    $q.all([
        p1.then(thenFn),
        p2.then(thenFn)
    ])
    .then(function(values) {
        $scope.fromThen = values;
    });
    
    // Must start the AngularJS digest process
    // to allow $q.resolve() to work properly
    // So use $timeOut() or $apply()
    
    setTimeout(function() {
        $scope.$apply(function() {
            console.log('resolving delayed promises');
            q1.resolve({
                value: 1
            });
            q2.resolve({
                value: 2
            });
        });
    }, 100, this);
    
    /* 
    *  Alternative approach
    *
    $timeout( function() {
    console.log('resolving delayed promises');
    q1.resolve({value : 1});
    q2.resolve({value : 2});        
});
*/
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="MyCtrl">
  {{fromThen}}
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.