1

I need to use a post to access a server side boolean method. It works fine in the controller like this.

$http.post(ROOT + '/step/ReadOnly/' + $scope.problemId)
        .success(function (result) {
            $scope.problemCompleted = result;

        })
    .error(function (data, status, headers, config) {
        console.log("problemCompleted not sent")
        return false;
    });

The problem is that I will be using this method in a lot of different controllers. So what I wanted to do is put the post into a service and just call it from there like this.

Service

//readOnly
this.readOnly = function (Id) {
    $http.post(ROOT + '/step/ReadOnly/' + Id)
        .success(function (result) {
            var problemCompleted = result;
            return problemCompleted;
        })
    .error(function (data, status, headers, config) {
        console.log("problemCompleted not sent")
        return false;
    });
};

and then call it in any controller like this.

$scope.problemCompleted = stepService.readOnly($scope.problemId);

It still calls the server side controller but the page seems to finish loading before it gets the response. The server side controller gets the right problemId . It just seems the page loads up before it gets the result from the post and my $scope.problemCompleted is undefined. It doesn't hit the .success or .error it just seems to skip over it so I don't get any result.

1 Answers1

1

You can't return from asynchronous code. What you can and should do in your case is return Promise object and in controller chain to its then-able API:

this.readOnly = function (Id) {
    return $http.post(ROOT + '/step/ReadOnly/' + Id).success(function (result) {
        return problemCompleted;
    })
    .error(function (data, status, headers, config) {
        console.log("problemCompleted not sent");
        return false;
    });
};

In controller:

stepService.readOnly($scope.problemId).then(function(data) {
    $scope.problemCompleted = data;    
});
Community
  • 1
  • 1
dfsq
  • 191,768
  • 25
  • 236
  • 258