Loading ...

Http Service And Promises

Hello everybody,

today another glimpse from the AngularJS world which I can name of how to get something from server.

So, imagine that you see following code in your controller:

 

var OrderController = function($scope, $http) {

    $scope.order = $http.get("/orders/1563");

}

and now is question, what's wrong with this? Just one very important issue, $http.get returns a promise, not the response itself. So in order to make it work correctly another approach will be more correct:

var OrderController = function($scope, $http) {

    var promise = $http.get("/orders/1563");

    promise.then(function(response){

      $scope.order = response.data;

          });

}

Why second approach is better? One of the reasons because promise give you guarantee that you'll receive data and display them correctly.

 

Be the first to rate this post

  • Currently 0.0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5