AngularJs检查每个请求的用户

时间:2016-03-27 14:44:03

标签: javascript angularjs

我正在尝试为每个请求识别用户。 现在这是我的locateExistingServerIfPossible文件:

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('/'); }); } })(); 使用看起来像这样的function run

authenticationFactory

但是现在我在控制台中收到错误:

  

routes.js:38 Uncaught TypeError:无法读取属性'then'   未定义

我做错了什么?

- 编辑 -

(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;
    }
})()

1 个答案:

答案 0 :(得分:0)

如果if子句失败,您的validateUser函数不会返回任何内容,解析机制总是希望返回一个promise。

尝试在if子句后添加此自动解析承诺,以充当 else

var q = $q.defer();
q.resolve();
return q.promise;

不要忘记将 $ q (AngularJS的承诺实施)注入服务。