user2322274 user2322274 - 6 months ago 15
AngularJS Question

How to assign value returned by service's $http.get() to a variable in controller?

I have created the separate service for fetching data from server, but I want to assign the data that this service returns to variable in the controllers. in this case data is a simple JSON file.

Here is my service

angular.module('app')
.service('TextService', ['$http', function CompanyService($http) {
var service = {};
$http.get('text.json').
then(function (response) {
service.text = response.data.text;
console.log(response.data.text);
}, function (response) {
alert(response);
});


return service;
}]);


and here is my controller

app.controller("myCtrl", ['$scope', 'TextService', function($scope, TextService){

$scope.text = TextService.text;


}]);


then I try to display $scope.text, but it does not work. (I have controller assigned in html)

<div class="content">
<h1>{{text}}</h1>
</div>


I guess I will need to use some helper function since, TextService is asynchronous. I would love to understand how to make it work and why it is not working now. and is it a good structure to wrap $http call in service?

Answer

Your service must provide methods to get text :

angular.module('app')
.service('TextService', ['$http', '$q', function CompanyService($http, $q) {
    var text;
    var service = {
      getText: function() {
          var defered = $q.defer();
          if(text == undefined) {
            $http.get('text.json').then(function success(data) {
              text = data.text;
              deferred.resolve(data.text); 
            },
             function error(err) { defered.reject(err) });
           }
           else {
             defered.resolve(text);
           }
           return defered.promise;
      }
  };
  return service;
}]);

And your controller call the service :

app.controller("myCtrl", ['$scope', 'TextService', function($scope,    TextService){
 TextService.getText().then(function(text) { $scope.text = text } );
}]);