1

This question has been asked before but this is more of what style to use. Currently we have several different controllers, and we keep making a REST call to get information. For example, $http.get('/allusers'). After we make this call, we create a user map to access each of these users. It works great but I don't like how we have to manually do this every time we need user information from the different controllers.

What I'd like is a shared object that has all the user information as a map and a shared function that will make the call and create/update the map.

This is where I start to get confused. What is the best and efficient way to approach this?

Liron Ilayev
  • 386
  • 4
  • 19
KingKongFrog
  • 13,946
  • 21
  • 75
  • 124

2 Answers2

0

You may want to have a Factory or a Service as I tried to explain here: https://stackoverflow.com/a/39933229/1005137

You may also want to cache the response from your $http request with the following: https://docs.angularjs.org/api/ng/service/$cacheFactory

Hope this helps.

Community
  • 1
  • 1
Aibu
  • 401
  • 5
  • 10
0

A service would be appropriate to use in this case. This would allow you to inject it into controllers, directives and components.

angular
  .module('myApp')
  .service('userService', UserService);

UserService.$inject = ['$http'];
function UserService ($http) {
   var service = this;

   service.getAllUsers = function () {
        return $http.get('/allusers');
   }
}

This would then allow you to inject and use in a controller

function UserController(userService) {
    userService.getAllUsers().then(function (response) {
        // response.data has your goods
    });
}
Graham
  • 7,431
  • 18
  • 59
  • 84
John F.
  • 4,780
  • 5
  • 28
  • 40