保存当前用户信息并在控制器中使用 [英] Save current user information and use it in controllers
问题描述
我有以下Angular服务:
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");
}
}
}
我正在获取有关当前用户的信息,例如ID,名称,...
I am getting information about the current user such as Id, Name, ...
我想在我的控制器中使用此信息,但是我不想每次需要该信息时都调用API(getAuthenticatedUserInfo)...有意义吗?
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?
推荐答案
在服务中创建一个局部变量,并将用户存储在其中.如果本地变量未定义,则仅执行HTTP调用.要确保始终返回一个承诺,无论本地用户是否可用,请使用$ q的when
函数:
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从不使用全局变量
PS never ever use global variables
这篇关于保存当前用户信息并在控制器中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!