Miguel Moura
Miguel Moura

Reputation: 39374

Save current user information and use it in controllers

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?

Upvotes: 3

Views: 1299

Answers (2)

fikkatra
fikkatra

Reputation: 5792

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

Upvotes: 3

thegio
thegio

Reputation: 1243

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;
     }
  }
}

Upvotes: 2

Related Questions