AngularJS向我的控制器注入新服务

时间:2014-08-01 20:45:40

标签: javascript angularjs dependency-injection angularjs-service angularjs-controller

我有一个新的userContext.js文件,它试图创建一个新的服务权限“userService”。该服务反过来将与服务器通信并返回一些环境设置以及用户会话ID。

当我从dashboard.js调用它进入我的datacontext.js控制器时,这一切都正常;但是我想为此实际创建一个服务。然后,我会在每个用户会话的整个生命周期中坚持这些会话变量。

在我最初尝试创建服务时,我遇到了很多注入器错误,例如:

       Error: [ng:areq] Argument 'fn' is not a function, got string

我已将其包含在我的index.html中:

  <script src="app/services/userContext.js"></script>

这是一个信息中心控制器代码段,我尝试注入'userService'

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

function dashboard($scope, $routeParams, $location, common, datacontext, userService) {
    var getLogFn = common.logger.getLogFn;
    var log = getLogFn(controllerId);

    var vm = this;

    getRzInitParams();

    function getRzInitParams() {
        log('Initializing Server Connection...');
        var rzParams = "";
        datacontext.getRzInitParams().then(function (data) {
            rzParams = data;
            initRz(data);
        });
    }
    function initRz(data) {         
        var response;
        datacontext.initRz().then(function (data) {
            response = data[0].split(":")                
            if (response[1].match(/SUCCESS/g)) {
                log('Server init returned ' + response[1].match(/SUCCESS/g));
                openUserSession();
            }
            else {
                log('Server init failed !');
            }

        });            
    }
 }
})();

这是来自datacontext.js的片段:

(function () {
'use strict';

var serviceId = 'datacontext';
angular.module('app').factory(serviceId, ['$http', 'common', datacontext]);

function datacontext($http, common) {
    var $q = common.$q;

    var service = {
        initRz: initRz,
        openUserSession: openUserSession,
        getRzInitParams: getRzInitParams
    };

    return service;

function initRz() {
        domain = "localhost:"
        port = "49479";
        controllerpath = "/api/init";
        space = "rz64698";
        env = "rz64698";
        cl_config = "C:\\Rz\\rz64698\\master\\bin\\cl_config.xml";

        var url = "http://" + domain + port + controllerpath + "?space=" + space + "&environment=" + env + "&clConfig=" + cl_config;
        var deferred = $q.defer();
        deferred.notify("Getting init parameters...");
        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);
        });
        return deferred.promise;
    }
    function getRzInitParams() {
        var deferred = $q.defer();
        var retval = [];
        $http({
            method: 'GET',
            encoding: 'JSON',
            url: 'breeze/breeze/GetRzEnv'
        }).success(function (data, status, headers, config) {
            retval = data;
            deferred.resolve(retval);
        });            
        return deferred.promise;
    }
  }
  })();

最后我正在创建新的'userService'服务:

     (function () {
'use strict';

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

app.service('userService', '$http', function () {
    // define private vars
    var _rzEnvParams = [];
    var _sessionID = '';

    this.initrz = function(domain, port, controllerpath, space, env, clariteconfig) {
        domain = "localhost:"
        port = "49479";
        controllerpath = "/api/init";
        space = "rz64698";
        env = "rz64698";
        cl_config = "C:\\rz\\rz64698\\master\\bin\\clarite_config.xml";

        var url = "http://" + domain + port + controllerpath + "?space=" + space + "&environment=" + env + "&clariteConfig=" + cl_config;
        var deferred = $q.defer();
        deferred.notify("Getting Rage init parameters...");
        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);
        });
        return deferred.promise;
    }
    this.getrzInitParams = function () {
        var deferred = $q.defer();
        deferred.notify("Getting Rage init parameters...");
        var retval = [];
        $http({
            method: 'GET',
            encoding: 'JSON',
            url: 'breeze/Rage/GetrzEnv'
        }).success(function (data, status, headers, config) {
            retval = data;
            deferred.resolve(retval);
        });
        return deferred.promise;
    }
    this.openUserSession = function() {
        domain = "localhost:"
        port = "49479";
        controllerpath = "/api/open";
        user = "";
        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);
        });
        return deferred.promise;
    }
    this.closeUserSession = function(domain, port, controllerpath) {

    }
});
 })();

2 个答案:

答案 0 :(得分:2)

如果你想注入一些服务,你应该使用这种语法之一

如果您只需要角度服务

app.service('userService', function ($http) {
 ...

如果您需要自定义服务

app.service('myService', ['$http', 'myOtherService', function($http, myOtherService) { 
... 
}])

答案 1 :(得分:1)

app.service('userService', '$http', function () {

应该像

app.service('userService', function ($http) {

希望这会有用