我想为我的整个应用程序设置一个全局。但它不起作用。这里我声明我的全局变量:AngularJs设置全球
(function() {
angular.module('employeeApp')
.controller('authenticationController', authenticationController)
.constant('GLOBALS', {
url:'http://skindustries.dev/api/v1/',
role:'',
companyid:'',
name:''
});
然后当员工登录时我想设置全局变量。
function authenticationController(requestFactory,authenticationFactory,GLOBALS,$location,$cookieStore)
{
var vm = this;
vm.login = function() {
data = {"email": vm.email, "password": vm.password};
requestFactory.post(GLOBALS.url + 'login', data)
.then(function (response) {
console.log(response);
GLOBALS.role = response.data.result.Employee.Role;
GLOBALS.companyid = response.data.result.Employee.CompanyId;
authenticationFactory.setToken(response.data.result.Employee.api_token);
$cookieStore.put('employeeid', response.data.result.Employee.EmployeeId);
$location.path('/home');
}, function() {
console.log('Niet ingelogd!');
});
}
}
如果我console.log(GLOBALS.role)
在authenticationController
结果是superadministrator
。然后用户被重定向回家。如果我在我的homeController
中console.log(GLOBALS.role)
。
(function()
{
angular.module('employeeApp').controller('homeController', homeController);
function homeController(employeeFactory,GLOBALS) {
console.log(GLOBALS.role);
结果是null
?
我在做什么错在这里!?
- 编辑 -
常数(服务)
(function() {
angular.module('employeeApp')
.service('constants',constants);
function constants() {
this.url = 'http://skindustries.dev/api/v1/';
this.role = 'oldRole',
this.companyid = '',
this.name = ''
}
})();
登录(工厂)
factory.login = function(email,password)
{
console.log('login');
data = {"email": email, "password": password};
requestFactory.post(GLOBALS.url + 'login', data)
.then(function (response) {
constants.role = response.data.result.Employee.Role;
constants.companyid = response.data.result.Employee.CompanyId;
factory.setToken(response.data.result.Employee.api_token);
$cookieStore.put('employeeid', response.data.result.Employee.EmployeeId);
$location.path('/home');
}, function() {
console.log('Niet ingelogd!');
});
}
的HomeController
(function()
{
angular.module('employeeApp').controller('homeController', homeController);
function homeController(constants) {
console.log(constants.role);
}
在''homeController'执行之前,您是否核对过'GLOBALS'正在被注册为角度常量? – nalinc
是的,我检查过! – Jamie
我建议你看看这篇关于auth的博客文章:http://www.jvandemo.com/learn-how-to-make-authentication-in-your-angular-applications-simpler-and-more -consistent/ –