Paolo B Paolo B - 4 months ago 17
AngularJS Question

AngularJS - get length of array from a webApi call on first call only

I am trying to display text 'showing X of Y Attractions' where X is the number currently showing and Y is the total number stored in the database.

I can get X easily by using

{{Attractions.length}}
- but I'm stuck on the best way to get Y?

Currently I am obtaining the data through a service call, which is just doing a
$http
get to a web api controller to get all of the data initially, which can then be filtered.

$scope.Attractions = dataService.getAllAttractions();


I would like to do something like:

$scope.totalAttractions = dataService.getAllAttractions().length;


So basically my question is what is the best way to get
totalAttractions
in this scenario?

Edit, my
getAllAttractions
dataservice function:

function getAllAttractions() {

$http.get("/api/v1/attractions")
.then(function (response) {
// Success
angular.copy(response.data, attractions);
}, function () {
// Failure
});
return attractions;
}

Answer

You are trying to return an undefined attractions with your getAllAttractions().

$http.get service is asynchronous and returns a promise. You should return that promise instead of attractions.

In your current code, I've inserted log display on the console.

function getAllAttractions() {

        $http.get("/api/v1/attractions")
            .then(function (response) {
                // Success
                console.log("success");
                angular.copy(response.data, attractions);
            }, function () {
                // Failure
                console.log("fail");
        });
        console.log("returned value");
        return attractions;
    }

Assuming you call the webservice successfully, console would probably display:

returned value
success

That is because the success callback is executed after you return attractions.

You should do this instead:

dataService

function getAllAttractions() {

        return $http.get("/api/v1/attractions");
    }

controller

dataService.getAllAttractions()
.then(function (response) {
        // Success
        $scope.attractions = response.data;
        $scope.totalAttractions = $scope.attractions.length;
}, function () {
        // Failure
});