Storing results of Angular Resource in Factory

310 Views Asked by At

I'm currently using Angular $resource to make an api, and I would like to keep those results in a service rather than a controller because every time I call the controller the results get called again, and thus any changes that were made get deleted.

I have tried answers given in several SO articles including:

AngularJS: Using Shared Service(with $resource) to share data between controllers, but how to define callback functions?

and

Angular Services/Factories with $resource

but neither of those have worked because I need the results stored in the service, but accessible for the controller.

Any help would be greatly appreciated.

2

There are 2 best solutions below

2
On

Since Angular's Services/Factories are singletons, if you just put the value of the callback on the services variable, you'll be able to get it from anywhere. Sample:

angular.module('foo',[])
  .service('FooService', ['$resource', function($resource){
      this.users = []
      $resource('/users')
         .get(function(users) {
            this.users = users
          })

     this.getUsers = function(){
       return this.users
     }
  })
  .controller('FooController', ['$scope','FooService', function($scope, FooService){
     $scope.users = FooService.getUsers()
  })

It's nice to remember that $resource is perfoming an asynchronous request to backend, so it would be nice to guarantee this data it's going to be available before you try to get it from the service.

1
On

Always use promises!

angular.module('foo',[])
  .service('FooService', ['$resource', function($resource){
    this.getUsers = function () {
      return $resource('/users', .get().$promise;
    };
  })
  .controller('FooController', ['$scope','FooService', function($scope, FooService){
    FooService.getUsers()
      .then(function (users) {
        $scope.users = users;
      });
  });

You could additionally refactor the $resource('/users') into a UserResource factory and inject UserResource into the service.