Returning HTTP data from an Angular service

I am sure this will be easy for any Angular / Javascript expert. I have a service that calls an API call to retrieve 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 it one of my controllers as follows:

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

However, my service is not quite right. It does not return a value outside the function of the HTTP request, so the data does not reach the controller that calls it. How to return data from both an HTTP request and a function?

+4
source share
2 answers

, . , . , Javascript . Angular - .

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

:

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

, : ?

+8

, . $resource . .

, data, , , $http . scope.division , .

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

+1

Source: https://habr.com/ru/post/1568138/


All Articles