我试图通过每个请求来识别用户。
现在这是我的 routes
文件:
(function () {
angular.module('employeeApp').config(routeModule).run(run);
routeModule.$inject = ['$routeProvider'];
function routeModule($routeProvider)
{
$routeProvider.when('/', {
templateUrl: '../views/login.html',
controller: 'authenticationController',
controllerAs: 'authenticationCtrl'
})
.when('/home', {
templateUrl: '../views/index.html',
controller: 'homeController',
controllerAs: 'homeCtrl',
resolve: {
message: function(authenticationFactory){
return authenticationFactory.validateUser();
}
}
})
.when('/werknemer/:id', {
templateUrl: '../views/employee/employee.html',
controller: 'employeeController',
controllerAs: 'employeeCtrl'
})
.otherwise({
redirectTo: '/'
});
}
function run(authenticationFactory)
{
authenticationFactory.validateUser()
.then(function (response) {
console.log('validateuser');
constants.firstname = response.data.result.Employee.FirstName;
constants.companyid = response.data.result.Employee.CompanyId;
constants.employeeid = response.data.result.Employee.EmployeeId;
}, function () {
$location.path('/');
});
}
})();
函数 run
使用 authenticationFactory
,如下所示:
(function()
{
angular.module('employeeApp').factory('authenticationFactory', authenticationFactory);
function authenticationFactory($cookieStore,$cookies,requestFactory,$location,GLOBALS,constants)
{
var factory = {};
factory.validateUser = function()
{
var vm = this;
if($location.path() != '/')
{
var api_token = factory.getToken();
factory.isValidToken(api_token).then(function(response) {
if (response.status != 200) {
$location.path('/');
}
data = {"api_token": api_token};
requestFactory.post(GLOBALS.url + 'show/employee/' + $cookies.get('employeeid'), data)
});
}
}
return factory;
}
})()
但是现在我在控制台中收到错误:
routes.js:38 Uncaught TypeError: Cannot read property 'then' of undefined
我做错了什么?
--编辑--
factory.validateUser = function()
{
var vm = this;
if($location.path() != '/')
{
var api_token = factory.getToken();
factory.isValidToken(api_token).then(function(response) {
if (response.status != 200) {
$location.path('/');
}
data = {"api_token": api_token};
return requestFactory.post(GLOBALS.url + 'show/employee/' + $cookies.get('employeeid'), data)
});
}
}
最佳答案
如果 if 子句失败,您的 validateUser 函数不会返回任何内容,解析机制始终期望返回一个 Promise。
尝试在 if 子句后面添加这个自动解析的 Promise,以用作 else:
var q = $q.defer();
q.resolve();
return q.promise;
不要忘记将 $q (AngularJS 的 Promise 实现)注入(inject)到服务中。
关于javascript - AngularJs 检查每个请求的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36248629/