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

前端 未结 2 1395
暗喜
暗喜 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 16:53

    Services should return the promise rather than the data. This is the asynchronous way.

    First fetch the value in the Angular's run method. For this example I put it in the $rootScope since that makes it accessible to all scopes in all controllers.

    AppName.run(['$http', '$rootScope',
        function($http, $rootScope) {
          console.log('Run');
          $http.get('http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo')
            .success(function(data) {
              $rootScope.resource = data;
              console.log($rootScope.resource);
            });
        }
      ])
    

    This is not really necessary unless you store it in some weird place.

    AppName.service('Resource',['$rootScope',
        function($rootScope) {
          return $rootScope.resource;
        }
      ]);
    

    Every scope will inherit the values in the $rootScope (thats why the service really isn't necessary.

    AppName.controller('mainController', ['$scope', 'Resource',
      function($scope, Resource) {
        console.log('controller');
        console.log(Resource);
      }
    ]);
    

    Warning!!! This value will not be available until after the first controller loads. If you use it in the controller just remember that you can bind it to html but the first pass through the controller code will not have initialized the variable yet.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题