编写AngularJS服务来保存数据

时间:2014-08-04 21:05:25

标签: angularjs

我试图编写一个很好的基于用户的服务,该服务应该保留一些会话变量。我在确定这方面遇到了一些麻烦,所以我们非常感谢您的指导。

这是" userService"角度服务:

请注意,我尝试在this.getrzInitParams中分配_rzEnvParams,并假设它将被保留,以便我可以从任何控制器获取值。

(function () {
'use strict';

var app = angular.module('app');    

app.service('userService', ['$http', 'common', userService] );

function userService($http, common){
    // define private vars
    var _rzEnvParams = {};
    var _sessionID = '';

    var _domain = '';
    var _port = '' ;
    var _controllerpath = '';
    var _space = '';
    var _env = '';
    var _clConfig = '';

    var $q = common.$q;

    this.initrz = function (rzEnvJson) {            
        _domain = rzEnvJson.domainName;
        _port = rzEnvJson.port; 
        _space = rzEnvJson.spaceName;
        _env = rzEnvJson.envName;
        _clConfig = rzEnvJson.clConfig; 
        _controllerpath = "/api/init";            
        var url = "http://" + _domain + ":" + _port + _controllerpath +
                "?space=" + _space + "&environment=" + _env +
                "&clConfig=" + _clConfig;
        var deferred = $q.defer();           
        var retval = [];            
        $http({
            method: 'GET',
            encoding: 'JSON',
            //data: "",
            headers: {
                'Access-Control-Allow-Origin': 'true'
            },
            withCredentials: true,
            url: url
        }).success(function (data, status, headers, config) {
            retval = data;
            deferred.resolve(retval);
        });
        return deferred.promise;
    }
    this.getrzInitParams = function () {
        var deferred = $q.defer();

        var rzEnvParams = [];
        $http({
            method: 'GET',
            encoding: 'JSON',
            url: 'breeze/breeze/GetrzEnv'
        }).success(function (data, status, headers, config) {
            rzEnvParams = data;
            deferred.resolve(rzEnvParams);                             
            _rzEnvParams = {
                "domain": _domain,
                "port": _port,
                "clConfig": _clConfig,
                "env": _env,
                "space": _space
            };
        });
        return deferred.promise;
    }
    this.openUserSession = function (rzEnvParams) {
        _rzEnvParams = rzEnvParams;

        _domain = _rzEnvParams.domainName;   // "localhost:";
        _port = _rzEnvParams.port;
        var controllerpath = "/api/open";
        var user = "";
        var pass = "";
        var url = "http://" + _domain + ":" + _port + controllerpath + "?userid=" + user + "&pass=" + pass;
        var deferred = $q.defer();
        deferred.notify("Opening user session...");
        var retval = [];
        $http({
            method: 'GET',
            encoding: 'JSON',
            headers: {
                'Access-Control-Allow-Origin': 'true'
            },
            withCredentials: true,
            url: url
        }).success(function (data, status, headers, config) {
            retval = data;
            deferred.resolve(retval);
        }).error(function (data, status, headers, config) {
            log("Cannot open a user session via api call. Errors details: " + data);
        });
        return deferred.promise;
    }
    this.closeUserSession = function(domain, port, controllerpath) {

    }
}
})();

在我的app.js中,我开始启动服务以初始化会话变量,但我的会话变量不会持续存在:

app.run(['$route', 'common', 'userService', function ($route, common, userService, getRzInitParams) {
    console.log("In app.run");
    var getLogFn = common.logger.getLogFn;
    var log = getLogFn('app');

    // initialize session with backend environment
    userService.getRzInitParams().then(function (rzEnvJson) {
        userService.initRz(rzEnvJson).then(function (data){
            var response = data[0].split(":")
            if (response[1].match(/SUCCESS/g)) {
                log('Backend server init returned ' + response[1].match(/SUCCESS/g));
                userService.openUserSession(rzEnvJson).then(function (data) {
                    response = data[0].split(",");
                    var status = response[0];
                    var sessionID = response[1].split('"')[1];
                });
            }
            else {
                log('Backend server init failed !');
            }
        });
    });

}]);

在我的控制器代码中,我试图访问我的会话变量 - _rzEnvParams和_sessionID:

(function () {
'use strict';
var controllerId = 'dashboard';
angular.module('app').controller(controllerId,
    ['$scope', '$routeParams', '$location', 'common', 'datacontext', 'gridHierarchyService', 'userService', dashboard]);

function dashboard($scope, $routeParams, $location, common, datacontext, gridHierarchyService, userService) {
    var vm = this;

    vm.sessionID = userService._sessionID;
    vm.rzEnvParams = userService._rzEnvParams;

 }
})();

1 个答案:

答案 0 :(得分:0)

我在控制器中发现了问题。您列出了字符串'$scope', '$routeParams'等,但在gridHierarchyService中有一个额外的字符串未在函数中列为参数。我相信您的userService会引用您的gridHierarchyService服务。