1
我試圖用每個請求來標識用戶。 現在這是我的routes
文件:AngularJs用每個請求檢查用戶
(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('/');
});
}
})();
的function 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)
});
}
}
'factory.validateUser'不返回請求承諾 –
即使我這樣做,我收到相同的錯誤!看我的編輯。 – Jamie
請參考關於[$ q]的文檔(https://docs.angularjs.org/api/ng/service/$q)你需要這個返回一個probise(來自'factory.validateUser')你解決/驗證過程後手動拒絕 –