I must have made a mistake somewhere and I know I am overlooking something obvious. The aim is to create a service that provides basic authentication features such as login, logout, and checking if a user is logged in or not.
Upon loading the page, I verify a cookie and try to fetch the user from the server if the session cookie indicates that the user is already logged in. I expect minimal full page transitions, but I believe having 1-2 full pages is probably the best approach, and I prefer not to store the user data in a cookie.
I grasped that a service is built by adding data/methods to the this object. I understand that the context of 'this' changes inside promises, but I'm puzzled as to why the this context points to the window object in the isLoggedIn method?
angular.module('myNgApplication').service('MyAuthentication', function ($cookies, UserProxy) {
this.user = null ;
(function(){
var SESSION_COOKIE = 'loggedIn'
if($cookies[SESSION_COOKIE]) {
var self = this
UserProxy.retrieveSession().then(function(authResponse){
console.log('init')
console.log(self)
self.user = authResponse
})
}
}).call(this)
this.isLoggedIn = function() {
console.log('isLoggedIn')
console.log(this)
return this.user != null ;
}
this.login = function (email, password) {
var self = this
return UserProxy.login(email, password).then(function(authResponse){
self.user = authResponse
return self.user
})
}
})
Usage:
var myWelcomeController = function($scope, MyAuthentication, $timeout) {
$scope.$watch(function(){ return MyAuthentication.user }, function() {
console.log(MyAuthentication.user)
$scope.user = MyAuthentication.user ;
$timeout(MyAuthentication.isLoggedIn, 1000)
});
};
Console:
init
Constructor {user: null, isLoggedIn: function, login: function}
isLoggedIn
Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}