user3800799 user3800799 - 5 months ago 7
AngularJS Question

Angular - $scope can't access $http response in a service

I have a service that I want to get data via

$http
(the reason for a service is because I need to make this call multiple times in my app)

The service is working great, this is the code:

factory('websiteService', function($rootScope, $http) {

this.getWebsites = function(){
http({
method: 'GET',
url: './data/websites.json'
}).then(function successCallback(response) {
return response.data;
});
}
$rootScope.websiteService = this;
return this;
});


Then, I'm using it in several controllers like so:

.controller('MyCtrl', function($scope, websiteService) {
$scope.websites = websiteService.getWebsites(); // not working
});


Though, as you guess this doesn't work. It seems that
websites
is defined before the
$http
request is ending, but I could be wrong.

How can I work around this?

Answer

Here's how the service should be defined:

myModule.factory('websiteService', function($http) {

    function getWebsites() {
        return $http({
            method: 'GET',
            url: './data/websites.json'
        }).then(function successCallback(response) {
            return response.data;
        });
    }

    return {
        getWebsites: getWebsites
    };
});

And here's how it should be used:

myModule.controller('MyCtrl', function($scope, websiteService) {
    websiteService.getWebsites().then(function(webSites) {
        $scope.webSites = webSites;
    });
});

I suggest you read Traps, anti-patterns and tips about AngularJS promises to understand the mistakes you made about promises.

Comments