AngularJs全球服务

时间:2016-03-25 13:22:31

标签: angularjs

我正在尝试将响应变量存储在全局服务变量中。这是我的service

(function() {
    angular.module('employeeApp')
        .service('constants',constants);

    function constants() {
        this.url = 'http://domain.dev/api/v1/';
            this.role =  '',
            this.companyid = '',
            this.name = ''
    }
})();

loginFactory:

factory.login = function(email,password)
        {
            var vm = this;
            vm.companyid = constants.companyid;

            data = {"email": email, "password": password};
            requestFactory.post(GLOBALS.url + 'login', data)
                .then(function (response) {
                    vm.role = response.data.result.Employee.Role;
                    vm.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中访问companyid时,它是空的。我究竟做错了什么。现在找几个小时但找不到解决方案!

3 个答案:

答案 0 :(得分:0)

您需要将常量服务注入loginFactory https://docs.angularjs.org/guide/di

.factory('loginFactory', ['constants', function(constants) {

此外,您没有在常量服务中返回对象

答案 1 :(得分:0)

嘿,你需要将你的服务作为依赖注入你的工厂

angular.module('employeeApp')
   .factory('loginFactory', ['constants', function(constants, $scope) {

$scope.login = function(email,password)
    {
        var vm = this;
        vm.companyid = constants.companyid;

        data = {"email": email, "password": password};
        requestFactory.post(GLOBALS.url + 'login', data)
            .then(function (response) {
                vm.role = response.data.result.Employee.Role;
                vm.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!');
            });
    }
  }

答案 2 :(得分:0)

除非您的应用的其他部分出现问题,否则这应该有效。注意函数constant中的分号而不是括号,并在模块声明中添加了方括号。

(function() {
    angular.module('employeeApp', [])
        .service('constants',constants);

    function constants() {
        this.url = 'http://domain.dev/api/v1/';
        this.role =  '';
        this.companyid = '';
        this.name = '';
    }
})();

请参阅Fiddle