0

I'm trying to pass data back to my controller from my service with no success. I am able to invoke my service from my controller, and I know the service itself works because I can console log the response from within the service (but not back in the controller).

This is my service:

(function () {
angular
    .module('app')
    .service('testService', testService);

testService.$inject = ['$http'];

function testService($http, url) {
    var baseUrl = "http://getjsondata.com/" + url;

    this.getData = function (url) {
        $http({
            method: 'GET',
            url: baseUrl + url,
            headers: {'Content-Type': 'application/json'}
        })
            .then(function (response) {
                console.log(response); // THIS WORKS
                return response;
            })
            .catch(function (error) {
                return error;
            });
    };
}
}());

This is inside my controller:

vm.getTestData = function (url) {
    vm.response = testService.getData(url);
    console.log(vm.response);
};

I've tried passing the data back as a callback in testService.getData but with no success. I have also tried using a factory instead of a service but I'm not able to access the data back in my controller. I have also tried defining my function in the service differently (getData: function()...) and so on.

I'm guessing my return statement in the service is behaving differently than the way I am expecting. I would appreciate any help!

3
  • getData never returns. add return in front of $http and use .then in your controller Commented Feb 4, 2018 at 13:16
  • @mr.void put that comment with a little detail in an answer. Explaining the problem to help others :-) Commented Feb 4, 2018 at 13:21
  • Please don't edit question to show the solution. That is what answers are for. The original problem should remain in order for answers to make contextual sense and not appear to duplicate what is in question Commented Feb 4, 2018 at 13:34

1 Answer 1

1

getData never returns. add return in front of $http and use .then in your controller.

this.getData = function (url) {
    return $http({
        method: 'GET',
        url: baseUrl + url,
        headers: {'Content-Type': 'application/json'}
    })
};

In ctrl

vm.getTestData = function (url) {
    testService.getData(url).then(function (response) {
        vm.response = response; 
        return response;
    })
    .catch(function (error) {
        return error;
    });
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.