简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM