Search code examples
javascriptangularjspromiseangularjs-serviceangular-promise

Can't get a value from $http promise and then() code not executed


I already had a problem with $http service in the past which I resolved by creating a service to handle my requests (for those who are interested, here's the link of the answer which helped me, the EDIT part : creating a service for $http request ).

The problem now is that this solution seems inefficient to handle bigger $http requests. In the previous one, I only assigned a word that were returned by the request to a $scope value. Now, what is returned is a whole configuration in JSON format (that I also want to store in the $scope).

I understand the concept of promises, the fact that the value returned by $http is a null string until the response comes, and that it could take time. But here, the configuration is not that long, and I never seem to get an answer ; I display the variable that recieves the value on the view and it doesn't change when the function is called.

Here's the code :

View

...
<div>
    {{loadedConfig}} 
</div>
<button ng-click="loadconfig()">load</button>

Controller

app.controller('ConfigurationCtrl', function ($scope, $rootScope, configloader) {
    ...
    $scope.loadedConfig = 'noconfig'
    $scope.loadconfig = function() {
        configloader.load().then(function (response) {
            $scope.loadedConfig = response.data;
        });
    };

Factory

angular
    .module('app')
    .factory('configloader', configloaderFactory);

function configloaderFactory($http) {

   var service = {
      load: load
   }

   return service;

   function load() {
      return $http.get('url/config');
   }
}

If I call a 'lesser weighted request', this works without a problem. I also tried other methods to make this call but in every case it didn't work... (with $q.deferred, with success()/error(), or with a custom sleep() function)

Is the code in the then supposed to execute when I get the response ? (I assume it is, but it never does).

Thanks


Solution

  • Try return the promise in you factory, somthing like :

    function load() {
         var promise =   $http.get('url/config').then(function(response){
         return response.data;     
         }, function(err){
           //error     
           return err;
         });
         return promise;
       }