Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Angularjs中访问currentUser_Angularjs - Fatal编程技术网

在Angularjs中访问currentUser

在Angularjs中访问currentUser,angularjs,Angularjs,目前,我的app.js配置中有以下代码,用于安全路由: var checkLoggedin = function($q, $timeout, $http, $location, $rootScope){ // Initialize a new promise var deferred = $q.defer(); // Make an AJAX call to check if the user is logged in $http.get('/api/loggedin').su

目前,我的app.js配置中有以下代码,用于安全路由:

var checkLoggedin = function($q, $timeout, $http, $location, $rootScope){
  // Initialize a new promise
  var deferred = $q.defer();

  // Make an AJAX call to check if the user is logged in
  $http.get('/api/loggedin').success(function(user){
    // Authenticated
    if (user !== '0')
      $rootScope.user = user; //IS THIS ADVISABLE???
      $timeout(deferred.resolve, 0);

    // Not Authenticated
    else {
      $timeout(function(){deferred.reject();}, 0);
      $location.url('/login');
    }
  });

  return deferred.promise;
};
后端返回用户对象

我希望能够从不同的控制器访问当前用户,并想知道我是否应该像上面所示使用$rootscope,或者是否应该使用服务


如果服务是前进的方向,那么任何代码示例都将非常受欢迎。

如果您只想在视图中使用您的用户变量,那么从rootScope读取就可以了。但是,如果您在控制器中希望使用该用户进行某些操作,则无法直接从rootScope读取,因为该变量可能尚未由checkLoggedin函数设置

例如,如果在控制器中有这样的代码

.controller('NavbarCtrl', function ($scope, $rootScope) {
    if ($rootScope.user) {
        // do logged in stuff
    }
    //...
它可能会失败,因为promise尚未在rootscope中设置用户变量

这有点烦人,但要保证变量总是设置好的,就需要把它当作承诺。所以我会尝试通过服务访问登录的用户

.service('PersonService', function ($http) {
        return {
            getCurrentUser: function() {
                return $http.get('/api/person/me', {cache: true});
                // or you can use something similar to your code above
            }
        }
    });
这就是一个例子。如您所见,我已启用缓存,因此对函数的多次调用不会创建对后端的新调用

然后像这样使用它:

.controller('NavbarCtrl', function ($scope, PersonService) {
    PersonService.getCurrentUser().success(function(user) {
        $scope.user = user;
        // or maybe do something else
        $scope.showButton = user.permissionLevel > 5;
    });
    // .....

谢谢目前,我只需要视图中的当前用户,因此我将坚持使用$rootScope,但您的额外示例非常好。我想,既然我每次加载页面都要打电话给后端,以确保他们已登录,那么为什么不使用返回的用户信息呢?这可能是一个更好的主意