3

I have the following Angular service:

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

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

function userService($http) {
  return { 
    getAuthenticatedUserInfo: function () {
      return $http.get("/api/v1/users/me");
    }     
  }
}

I am getting information about the current user such as Id, Name, ...

I want to use this information in my controllers but I do not want to call the API (getAuthenticatedUserInfo) everytime I need that information ... Does it make sense?

What is the best option use this information in other controllers?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481
  • Possible duplicate of [How do I store a current user context in Angular?](https://stackoverflow.com/questions/14206492/how-do-i-store-a-current-user-context-in-angular) – Rumid Mar 22 '18 at 13:58

2 Answers2

3

Create a local variable within the service and store the user in there. Only perform the HTTP call if the local variable is undefined. To make sure you always return a promise, whether the local user is available or not, use $q's when function:

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

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

function userService($http, $q) {

    var currentUser;
  return { 
    getAuthenticatedUserInfo: function () {
        if (currentUser){
            return $q.when(currentUser);            
        } else {
            return $http.get("/api/v1/users/me").then(function(response) {
                currentUser = response.data;
                return response.data;
            });
        }

    }     
  }
}

PS never ever use global variables

fikkatra
  • 5,605
  • 4
  • 40
  • 66
  • Between using this approach or saving user info in session after login which one is better? – Miguel Moura Apr 15 '16 at 11:32
  • 1
    What exactly do you mean by 'in session'? With this solution, your state will be lost if the user refreshes the page. You might want to store the user in localstorage if you want the user to be persisted accross page reloads. – fikkatra Apr 15 '16 at 11:35
  • Of course, you are right ... This is enough in my case. Thanks – Miguel Moura Apr 15 '16 at 11:46
  • I spotted one issue in this solution, it will perform multiple requests until the first promise returns. – thegio Apr 17 '16 at 20:14
2

I would use a local variable and check if it is null, otherwise you perform the GET request.

Example:

function userService($http) {

var cached = null;

return { 
     current: function () {
         var u = $http.get("/api/v1/users/me");
         cached = u;
         return u;
     },

    currentCachedUser: function () {
      if (cached == null) {
         cached = this.current();
     }
     return cached;
     }
  }
}
thegio
  • 1,233
  • 7
  • 27