You could use a watch function:
$scope.$watch(function() {
return session.isAuthenticated();
},
function() {
$log.info "currentUser: " + session.currentUser + " ; isAuth: " + session.isAuthenticated()
}
);
Pregunta
Updated: code in JS
I borrowed auth (session) service from angular-app, and strongly modify it:
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
])
This is an app:
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()
])
So, i guess, when the application starts the currentUser is requested (perhaps a controller starts working before the callback of the request, but the problem in other place). Next, Controllers:
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()
])
The point is that isAuthenticated()
always false
, but currentUser
not null when a user is logged in. So, when i logged in $log.info
shows currentUser: [object Object] ; isAuth: false
and not only when the site just loaded, but when i'm navigating too. When i logged out it shows currentUser: null ; isAuth: false
. Obviously, currentUser
is always null inside the service. But how can i define it to be able change the value?
Solución
You could use a watch function:
$scope.$watch(function() {
return session.isAuthenticated();
},
function() {
$log.info "currentUser: " + session.currentUser + " ; isAuth: " + session.isAuthenticated()
}
);
Otros consejos
update isAuthenticated to
isAuthenticated: ->
service.currentUser?
although this is async you should use resolve in router.