AngularJs auth服务表现奇怪

时间:2013-10-13 08:09:40

标签: javascript angularjs authentication coffeescript angular-services

已更新code in JS

我从angular-app借用了auth(会话)服务,并强烈修改它:

  angular.module('auth', [])
    .factory('session', ['$location', '$http', '$q', ($location, $http, $q) ->

      service =

        requestCurrentUser: ->
          if service.isAuthenticated()
            $q.when service.currentUser
          else
            $http.get('/user').then (response) ->
              console.log(response.data)
              service.currentUser = response.data
              service.currentUser

        currentUser: null

        isAuthenticated: ->
          not service.currentUser?

      service
    ])

这是一款应用:

  BookReader = angular.module('BookReader', ['ngRoute', 'home', 'main', 'books', 'auth'])

  BookReader
    .config(['$routeProvider', '$httpProvider', '$locationProvider', ($routeProvider, $httpProvider, $locationProvider) ->
      $routeProvider
        .when '/',
          templateUrl: 'assets/tour.html'
          controller: 'MainCtrl'
        .when '/home',
          templateUrl: 'assets/main.html'
          controller: 'HomeCtrl'
        .when '/books',
          templateUrl: 'assets/books.html'
          controller: 'BooksCtrl'
    ])
    .run(['session', (session) ->
      session.requestCurrentUser()
    ])

所以,我想,当应用程序启动时,请求currentUser(可能是控制器在回调请求之前开始工作,但问题在其他地方)。接下来,控制器:

angular.module('main', ['ngCookies'])
  .controller('MainCtrl', ['$scope', '$http', '$cookies', '$location', 'session', '$log',
    ($scope, $http, $cookies, $location, session, $log) ->
      $log.info "currentUser: " + session.currentUser + " ; isAuth: " + session.isAuthenticated()
      $location.path '/home' if session.isAuthenticated()
  ])


angular.module('home', ['ngCookies'])
  .controller('HomeCtrl', ['$scope', '$http', '$cookies', 'session', '$location', '$log'
    ($scope, $http, $cookies, session, $location, $log) ->
      $log.info "currentUser: " + session.currentUser + " ; isAuth: " + session.isAuthenticated()
      $location.path '/' unless session.isAuthenticated()
  ])

关键是isAuthenticated()总是false,但currentUser在用户登录时不为空。因此,当我登录$log.info时显示{{1}而且不仅在网站刚刚加载时,而且我在导航时也是如此。当我退出时显示currentUser: [object Object] ; isAuth: false。显然,currentUser: null ; isAuth: false在服务中始终为null。但是我如何定义它才能改变价值?

2 个答案:

答案 0 :(得分:1)

您可以使用监视功能:

$scope.$watch(function() {
   return session.isAuthenticated();
 },
 function() {
   $log.info "currentUser: " + session.currentUser + " ; isAuth: " + session.isAuthenticated()
 }
);

答案 1 :(得分:1)

更新isAuthenticated to

isAuthenticated: ->
      service.currentUser?

虽然这是异步的,但你应该在路由器中使用resolve。