更新:JS中的代码
我从angular-app借用了 auth (session) 服务,并对其进行了强烈修改:
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
不是 null。所以,当我登录时,不仅$log.info
显示currentUser: [object Object] ; isAuth: false
网站刚刚加载时,而且当我也在导航时。当我注销时它显示currentUser: null ; isAuth: false
。显然,currentUser
在服务内部始终为空。但是我如何定义它才能改变值?