Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

javascript - (Angularjs) How to $http.get data and store it in service

As you will see i'm new in AngularJS, JS and in web development at all =) really sorry for that but i try to.

I try to build a massive webform (about 200 different fields) with AngularJS controllers. I need access from controller to root data source. AngularJS team ask do not make Services just for storing data, but i want to make service for load and save data (at start into .json files on a server).

Service:

AppName.factory('MasterData', ['$rootScope', '$http', '$q', '$log', 
    function($rootScope, $http, $q, $log) {

    var responseData;
    $http.get('/getdata.php').then(function (response) {
        responseData = response.data;
        console.log(response.data);
    });

    return responseData;

}]);

Controller:

AppName.controller('justController', ['$scope', 'MasterData', '$log',
    function ($scope, MasterData, $log) {
        $scope.data = MasterData.justControllerSectionData;
        console.log(MasterData);
    }
]);

Controller return undefined. But console.log from service returns the object. I feel that the problem is too easy, but i can't find how to solve it :( Also i can't use function like .getData() from controller to service because it ask the data from server each time any controller loads. I have the routes in AngularJS app with 12-14 controllers (full webform divided by sections) and i think it is good to get the data from backend once.

P.S. I think there is problem with promises, but when i try to use code like this:

var defer = $q.defer();
$http.get('/getdata.php').success(function(data){
    defer.resolve(data);
});
return defer;

I've got object with resolve, reject and so on. And really can't understand what can i do with it :(

Help me to get the data in controller :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your code doesn't work, because the callback you supplied to success() in your service is called asynchronously; after your service has returned, that is:

The sequence is like this:

  1. The function in MasterData is run. The $http.get request is launched and attached the promise callback. responseData is referenced in this callback (aka. "closed over").
  2. The function returns from the service to your controller. responseData has not been set yet, which doesn't stop the parent scope function from returning.
  3. $http.get succeeds and responseData is set in the service however unreachable for the controller.

If the scoping of the nested function in success() is not clear to you, I'd recommend reading about closures in JavaScript (or even better, in general), for example here.

You can achieve your goal with a service like this:

function($q, $http, /* ... */) {    
    return {
        getData: function() {
            var defer = $q.defer();
            $http.get('/getdata.php', { cache: 'true'})
            .then(function(response) {
                defer.resolve(response);
            });

            return defer.promise;
    };
}

The $http service will happily cache your response data, so you don't have to. Note that you need to retrieve the promise from your deferred object to make this work.

The controller is like this:

/* omitted */ function($scope, YourService) {
    YourService.getData().then(function(response) {
        $scope.data = response.data;
    });
}

Since success is depreciated, I modified success to then.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...