0

I have been stuck on this for quite a while now and cannot figure out why the value is not being returned. I am using Angular $resource to make a GET request to an API.

My $resource factory looks like this:

.factory("Bookings", function ($resource) {
    return $resource("www.example/bookings_on_date/:day", {});
})

I have tried to implement promises but am unable to do so correctly.

function getBookings(day){
        return Bookings.get({"day": day}).$promise.then(function(data) {
        console.log(data.total)
        return data.total;
    });
}

$scope.todaysBookings = getBookings(TODAY);
$scope.tomorrowsBookings = getBookings(TOMORROW);

When I view either console.log($scope.todaysBookings) or $scope.tomorrowBookings in the console it returns undefined.

I have also tried everything from this jsfiddle but unfortunately have not had any luck.

Paul Fitzgerald
  • 11,770
  • 4
  • 42
  • 54

1 Answers1

2

I think it should be like this:

function getBookings(day) {
    return Bookings.get({"day": day}).$promise.then(function(data) {
        return data.total;
    });
}

getBookings(TODAY).then(function(total) {
    $scope.todaysBookings = total;
});

getBookings(TOMORROW).then(function(total) {
    $scope.tomorrowsBookings = total;
});

Update: I think next code style could help you to prevent next extending method problems:

function getBookings(args) {
    return Bookings.get(args).$promise;
}

getBookings({"day": TODAY}).then(function(data) {
    $scope.todaysBookings = data.total;
});

getBookings({"day": TOMORROW}).then(function(data) {
    $scope.tomorrowsBookings = data.total;
});

A little advantages here:

  • Pass object into function could help you easily pass different arguments into method and arguments are very close to method call (a little bit easy to read);
  • Return complete response from function could help you to process different data (method could replay different response depends on arguments, but it's not good practise in this case);

p.s. Otherwise, you could remove function declaration and code like this (to keep it as simple, as possible):

Bookings.get({"day": TODAY}).$promise.then(function(data) {
    $scope.todaysBookings = data.total;
});

Bookings.get({"day": TOMORROW}).$promise.then(function(data) {
    $scope.tomorrowsBookings = data.total;
});
Maxim Zhukov
  • 10,060
  • 5
  • 44
  • 88