Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return http data from Angular service

I'm sure this will be an easy one for any Angular/Javascript experts. I have a service that makes a call to an API to get some data:

app.service("GetDivision", ["$http", function($http){

  this.division = function(divisionNumber){
    $http.post("/api/division", {division:divisionNumber}).success(function(data){
      return data;
    });
  } 

}]);

Now I call this in one of my controllers like so:

$scope.division = GetDivision.division(1);

However, my service isn't quite right. It doesn't return the value outside of the http request function, so the data doesn't reach the controller calling it. How do I return the data out of both the http request and the function called?

like image 523
CaribouCode Avatar asked Jan 10 '23 05:01

CaribouCode


2 Answers

You need to understand that you can't return from asynchronous operations. Response is simply not yet available when you try to return data. Typically in Javascript you would use callback or promise pattern. In Angular promise is a very natural choice.

app.service("GetDivision", ["$http", function($http) {
  this.division = function(divisionNumber){
    return $http.post("/api/division", {division:divisionNumber}).success(function(data){
      return data;
    });
  }
}]);

and in controller:

GetDivision.division(1).then(function(data) {
    $scope.division = data;
});

Make sure you read this very popular thread on the subject: How do I return the response from an asynchronous call?

like image 173
dfsq Avatar answered Jan 19 '23 00:01

dfsq


You can return empty object from your service and populate it once you receive the response. That is the way $resource service do it. It also allows to avoid additional logic in controller.

This will work because reference to data object that is put into the scope remains the same all the time and $http service starts digest cycle once response is returned. Therefore the change in the scope.division will be immediately detected and view will be updated accordingly.

JavaScript

var app = angular.module('app',[]);

app.service("GetDivision", ["$http", function($http){

  var data = {};

  this.division = function(divisionNumber){
    $http.get("division", {division:divisionNumber}).success(function(responseData){
      angular.extend(data, responseData);
    });
    return data;
  } 

}]);

app.controller('ctrl', ['$scope', 'GetDivision', function ($scope, GetDivision) {
  $scope.division = GetDivision.division(1);
}]);

HTML

<body ng-controller="ctrl">
  <h1>{{division.text}}</h1>
</body>

Live Demo: http://plnkr.co/edit/H31mSaXiiCiVG9BA9aHK?p=preview

like image 33
Vadim Avatar answered Jan 19 '23 00:01

Vadim