3

I'm trying to return the values I get in my $http.get but I can't get it to work...

$scope.getDecision = function(id) {
    var defer = $q.defer();
    $http({
        method: 'GET',
        url: 'http://127.0.0.1:3000/decision',
        params: {id: id},
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).success(function(data, status, header, config) {
        console.log(data); //----> Correct values
        defer.resolve(data);
    }).error(function(data, status, header, config) {
        defer.reject("Something went wrong when getting decision);
    });
    return defer.promise;
};

$scope.selectView = function(id) {
     var decision = $scope.getDecision(id);
     console.log(decision); //----> undefined
}

When I call selectView I want to get a decision, but all I get is undefined... Have I misunderstood the promise pattern? :S

3

2 Answers 2

3

$http itself returns a promise. No need to form your own, just do return $http(...).

Sign up to request clarification or add additional context in comments.

1 Comment

I removed your .get call since OP is using $http with options object, hope you don't mind :)
0

$http returns a Promise anyway, so you don't really need to create your own, but the main reason this isn't working is that you still need to .then your getDecision call in order to wait for the asynchronous operation to complete, e.g.

$scope.selectView = function(id) {
     $scope.getDecision(id).then(function(decision) {
          console.log(decision);
     });
}

To use the existing $http promise:

$scope.getDecision = function(id) {
    return $http({
        method: 'GET',
        url: 'http://127.0.0.1:3000/decision',
        params: {id: id},
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    });
};

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.