1

I have the following scenario, I need data from a particular url.I also need to save this datas into a variable that I can call everywhere in my controller. To overcome such issue, I have written a service like below :

app.service("userData", function ($http, $q) {

var deferred = $q.defer();

this.getUsers = function () {
    return $http.get('/users')
        .then(function (response) {
            deferred.resolve(response.data);
            return deferred.promise;
        }, function (response) { 
            deferred.reject(response);
            return deferred.promise;
        })
    ;
};
});

And then my controller looks like :

  app.controller('UserCtrl', function($scope, $q, userData) {
  var myData = userData.getUsers()
  .then(
      function (result) {
          $scope.users = result;
      },
      function (error) {
          console.log(error.statusText);
      }
  );
  console.log(myData)
  });

It prints :

print screen

So how can i store data into a variable which is accessible all over the controller ? Thanks..

Daniel
  • 584
  • 3
  • 8
  • 20
  • Welcome to the wonderful world of **async**! You can't do that. http://blog.slaks.net/2015-01-04/async-method-patterns/ – SLaks Apr 17 '16 at 18:36
  • `$http.get` already returns a promise. Your `deferred` is completely useless – SLaks Apr 17 '16 at 18:37

1 Answers1

1

I suggest you something like that:

    angular.module("app").factory("userService", userService);

    userService.$inject = ["$http", "$q"];

function userService($http, $q) {
    var deferred = $q.defer();
    var promise = null;
    var currentUser = null;
    return {
        getUserInfo: function () {
            if (promise) {
                deferred.resolve(currentUser);
                return (currentUser) ? deferred.promise : promise;
            }
            else {
                promise = $http.get("http://swapi.co/api/people/1/").then(function (response) {
                    return currentUser = response.data.name;
                });
                return promise;
            }    
        }
    }
}

you can call then any time userService.getUserInfo() to get the cached data.

   .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/view1', {
            templateUrl: 'view1/view1.html',
            controller: 'View1Ctrl',
            controllerAs: 'vc'
        });
    }])

    .controller('View1Ctrl', function (userService) {
            var vm = this;
            userService.getUserInfo().then(function (result) {
                vm.name = result
            }, function (err) {
                vm.name = err
            });
        });

I create a git repository to test it out: https://github.com/leader80/angular-cache-service

I hope it helps

thegio
  • 1,233
  • 7
  • 27