Я очень запутан из-за этого свойства.
Что означает " delete this.user;
", означает " AuthenticationFactory
. Я думаю, что функция " check
" - это метод, поэтому он будет связываться с объектом " auth
". Но в объекте " auth
" нет свойства " user
". Вы можете это объяснить?
Кроме того, в " UserAuthFactory
" (delete AuthenticationFactory.user
, delete AuthenticationFactory.userRole
)
Я не могу понять, что userRole
свойства " user
" и " userRole
". В AuthenticationFactory
таких свойств нет.
Здесь мой код от http://thejackalofjavascript.com/architecting-a-restful-node-js-app/
myApp.factory('AuthenticationFactory', function($window) {
var auth = {
isLogged: false,
check: function() {
if ($window.sessionStorage.token && $window.sessionStorage.user) {
this.isLogged = true;
} else {
this.isLogged = false;
delete this.user;
}
}
}
return auth;
});
myApp.factory('UserAuthFactory', function($window, $location, $http, AuthenticationFactory) {
return {
login: function(username, password) {
return $http.post('http://localhost:3000/login', {
username: username,
password: password
});
},
logout: function() {
if (AuthenticationFactory.isLogged) {
AuthenticationFactory.isLogged = false;
delete AuthenticationFactory.user;
delete AuthenticationFactory.userRole;
delete $window.sessionStorage.token;
delete $window.sessionStorage.user;
delete $window.sessionStorage.userRole;
$location.path("/login");
}
}
}
});
Если вы посмотрите дальше, на код контроллера:
$scope.login = function() {
var username = $scope.user.username,
password = $scope.user.password;
if (username !== undefined && password !== undefined) {
UserAuthFactory.login(username, password).success(function(data) {
AuthenticationFactory.isLogged = true;
AuthenticationFactory.user = data.user.username;
AuthenticationFactory.userRole = data.user.role;
$window.sessionStorage.token = data.token;
$window.sessionStorage.user = data.user.username; // to fetch the user details on refresh
$window.sessionStorage.userRole = data.user.role; // to fetch the user details on refresh
$location.path("/");
}).error(function(status) {
alert('Oops something went wrong!');
});
} else {
alert('Invalid credentials');
}
};
При успешном входе в систему контроллер добавляет свойства user
и userRole
в AuthenticationFactory.