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

前端 未结 2 1403
暗喜
暗喜 2020-12-13 16:16

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

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-13 17:05

    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.

提交回复
热议问题