我想获得一个主题的帮助。我已经为登录过程创建了AuthService。登录后,用户将被重定向到主页。 Homepage有一个名为ApplicationController的控制器。该控制器正在观察AuthService的变量变化。在此步骤中,AuthService.getUser()
返回undefined。我搜索了解决方案并应用了所有推荐的解决方案,但仍然没有变化。有人能帮助我理解这个问题吗?
LoginController.js
app.controller('LoginController', ['$scope', '$window', 'AuthService', function ($scope, $window, AuthService) {
$scope.username = null;
$scope.password = null;
$scope.error = null;
$scope.login = function () {
$scope.error = null;
AuthService.login({ username: $scope.username, password: $scope.password },
function success(data, status, headers, config) {
// redirect to homepage, which has ApplicationController
$window.location = "/";
},
function error(data, status, headers, config) {
$scope.error = data.error_description;
});
}
}]);
AuthService.js
app.factory('AuthService', function ($http) {
var authService = {};
var currentUser;
authService.login = function (credentials, successCallback, errorCallback) {
$http({
// do some $http config
}).success(function (data, status) {
var loggedInUser = {
Username: data.Username,
Name: data.Name,
Surname: data.Surname,
Email: data.Email,
ID: data.ID,
MobileNumber: data.MobileNumber,
Role: data.Role
};
currentUser = loggedInUser; // here set the currentUser
successCallback(data, status);
}).error(function (data, status) {
errorCallback(data, status);
});
};
authService.isLoggedIn = function () {
return currentUser != undefined ? true : false;
};
authService.getUser = function () {
return currentUser;
};
return authService;
})
ApplicationController.js
app.controller('ApplicationController', function ($scope, $location, $window, AuthService) {
$scope.currentUser;
$scope.isAuthenticated;
$scope.$watch(AuthService.isLoggedIn, function (isLoggedIn) {
// here AuthService.getUser() returns undefined.
$scope.currentUser = AuthService.getUser();
});
});
答案 0 :(得分:0)
ApplicationController应该正在观看AuthService.isLoggedIn
的返回值,所以:
$scope.$watch(function () {
return AuthService.isLoggedIn();
}, function (isLoggedIn) {
不
$scope.$watch(AuthService.isLoggedIn, function (isLoggedIn) {
答案 1 :(得分:0)
$ scope。$ watch接受函数作为监视表达式,因此您可以返回isLoggedIn
的值app.controller('ApplicationController', function ($scope, $location, $window, AuthService) {
$scope.currentUser;
$scope.isAuthenticated;
$scope.$watch(function () {return AuthService.isLoggedIn();}, function (isLoggedIn) {
// here AuthService.getUser() returns undefined.
$scope.currentUser = AuthService.getUser();
});
});