Search code examples
angularjsangularjs-service

How can I get a service to access server data via an $http call?


I make an $http call inside a service that is supposed to get data from my server. For some reason I can't get my service to work - nothing happens. I know the server code works because if I place the $http call inside a function within my controller, then it gets the server data as expected. Here is the code I have so far:

app.service('myService', function($q,$compile,$http) {
    this.getData = function() {
        var deferred = $q.defer();
        var promise = $http.get('myfile.php').success(function (data) {
            var response = $compile(data)($scope);
            deferred.resolve(response);
        });
        return deferred.promise; 
    };
});

Also, I know the code that uses this service works because if I do something like the following,

app.service('myService', function() {
    this.getData = function() {
        return 'TEST';
    };
});

then I will see the word "TEST" show up in the div that utilizes this service. I feel like I'm very close, but there is something I am missing. Any ideas on what I'm doing wrong?

UPDATE:

controller: function($scope, $http, $rootScope, myService){
    var scope = $rootScope;
    scope.viewMyData = function() {
        var element = myService.getData();
        $('#myDiv').html(element);
    }
}

HTML:

<div ng-click="viewMyData()">Click Here</div>
<div id="myDiv"></div>

If I strip the code in myService and simply return TEST (as above), then I will see "TEST" show up in id="myDiv". But for some reason the $http call isn't being triggered.


Solution

  • @tymeJV is right, but here's my attempt to spell out the example better. $http returns a promise interface that allows you to chain callbacks to be executed when the $http response returns. So, in this case, calling myService.getData() can't return the result immediately (it's off getting the data from the server), so you need to give it a function to execute when the server finally responds. So, with promises, you simply attach your callback using the thePromise.then(myCallbackFunc).

    Service

    app.service('myService', function($q,$compile,$http) {
        this.getData = function() {
            var promise = $http.get('myfile.php');
            promise = promise.then(function (response) {
                return response.data;
            });
            return promise;
        };
    });
    

    Controller

    controller: function($scope, $rootScope, myService){
        var scope = $rootScope;
        scope.viewMyData = function() {
            myService.getData().then(function(data) {
                $('#myDiv').html(element);
            });
        }
    }