-1

I want to use Angular's $http but I'm not sure what to do with what it returns.

The main thing that is troubling me is that it returns an HttpPromise. What do I do with that? How does it work?

CodyBugstein
  • 21,984
  • 61
  • 207
  • 363

1 Answers1

0

It's really simple. Angular's $http returns a Promise, which is like any other kind of Promise and I recommend you read up on Angular's $q

In the following JSFiddle, the HttpPromise is used a few seconds after it's executed. In other words, $http.get(...) is issued, but we only do something with the result later, at our leisure.

JSFiddle

function Ctrl($scope, $http, $timeout) {
    $scope.text = "text";
    $scope.clicky = function(){
        var httpPromise = $http.get('/echo/json/');

        $timeout(function(){
            httpPromise.success(function(data){
                $scope.text = "Http Post Worked Succesfully";
                console.log(data);
            });
        }, 3000);
    }
}
Community
  • 1
  • 1
CodyBugstein
  • 21,984
  • 61
  • 207
  • 363
  • Rick Strahl has a good article about the differences between HTTP promises and "regular" promises. I recommend just using the regular promise syntax with them, despite the AngularJS documentation though. http://weblog.west-wind.com/posts/2014/Oct/24/AngularJs-and-Promises-with-the-http-Service – John Bledsoe Mar 09 '15 at 15:20
  • This approach would work, but it's completely useless to "wait". You are right that you can pass the promise around and resolve it wherever (or whenever) you want, but this is not the intent of promises. The intent of promises is to make code composition of async calls resemble syncronous code – New Dev Mar 20 '15 at 15:09