0

I have this function, which I call loadAll() at the top.

function loadAll() {      
        UniversalService.GetAll()
            .then(function (a) {
                $scope.all = a;

            });
    }

when I use it inside my html I get correct information, but I need these values later in my controller for pagination, so I call it // get current page of items $scope.items = $scope.all.slice(vm.pager.startIndex, vm.pager.endIndex + 1);

But I dont't get any values.

user122222
  • 2,179
  • 4
  • 35
  • 78

2 Answers2

1

You may call this before this promise is resolved? Adding this in the resolved promise may be your solution.

function loadAll() {      
        UniversalService.GetAll()
            .then(function (a) {
                $scope.all = a;
                $scope.items = $scope.all.slice(vm.pager.startIndex, vm.pager.endIndex + 1);
            });
    }

Or use a callback if you wont change this function:

    function loadAll(callback) {      
            UniversalService.GetAll()
                .then(function (a) {
                    $scope.all = a;
                    if (callback) {
                        callback();
                    }
                });
        }

and call it like:

loadAll(function() {
    $scope.items = $scope.all.slice(vm.pager.startIndex, vm.pager.endIndex + 1);
});
Fetrarij
  • 7,176
  • 3
  • 27
  • 35
  • Is it possible to solve promise in other way? I can't call ` $scope.items = $scope.all.slice(vm.pager.startIndex, vm.pager.endIndex + 1);` in loadAll() function because this line is used in another function – user122222 Jun 25 '17 at 08:51
  • Yes it is possible but why not an optional callback? I edited the answer. – Fetrarij Jun 25 '17 at 09:00
  • 1
    The callback pattern is not recommended with promises. See [Why are Callbacks from Promise `.then` Methods an Anti-Pattern](https://stackoverflow.com/questions/35660881/why-are-callbacks-from-promise-then-methods-an-anti-pattern). – georgeawg Jun 25 '17 at 10:22
1

Is it possible to solve promise in other way? I can't call $scope.items = $scope.all.slice(vm.pager.startIndex, vm.pager.endIndex + 1); in loadAll() function because this line is used in another function

Return a promise from UniversalService.GetAll():

function loadAll() {      
    var promise = UniversalService.GetAll();
    promise.then(function (all) {
        $scope.all = all;
    });
    //RETURN promise
    return promise;
}

Then use that promise in another function:

var loadAllPromise = loadAll();

function another(loadAllPromise) {
    loadAllPromise.then(function(all) {
        $scope.items = all.slice(vm.pager.startIndex, vm.pager.endIndex + 1);
    });
}
georgeawg
  • 48,608
  • 13
  • 72
  • 95