角度服务内部的功能不被视为一种功能(再次)

时间:2015-09-18 16:31:41

标签: javascript angularjs

所以,我的服务声明如下:

var StateService = angular.module('StateService', [])
.service('HoldState', function ($http, $q) {

在该服务内部,我有以下功能:

this.setTypeOfLaw = function (a) { localStorage.setItem('LawType', a) };
    this.setCourthouse = function (a) { localStorage.setItem('Building', a) };
    this.setDepartment = function (a) { localStorage.setItem('Dept', a) };
    this.getTypeOfLaw = function () {
        var LT = localStorage.getItem('LawType');
        return LT;
    };
    this.getCourthouse = function () {
        var BLDG = localStorage.getItem('Building');
        return BLDG;
    };
    this.getDepartment = function () {
        var DEPT = localStorage.getItem('Dept');
        return DEPT;
    };

我的控制器按如下方式注入我的服务:

JBenchApp.controller('CaseListCtrl', ['$scope', '$http', 'HoldState', 
  function ($scope, $http, HoldState) {

它也会在app.js文件中注入。

如果我向控制器添加代码

var a = HoldState.getDepartment();

我收到一条错误,指出“getDepartment”不是一个函数。什么?

3 个答案:

答案 0 :(得分:1)

可以按如下方式将方法添加到服务中

var StateService = angular.module('StateService', [])
.service('HoldState', function ($http, $q) {
 return {
      getDepartment : function() {
      ...
      }
   }
}

然后访问:

HoldState.getDepartment();

希望这有帮助。

答案 1 :(得分:1)

单身人士角色的服务,工厂和提供商,注入时需要返回公共API。

var StateService = angular.module('StateService', [])
.service('HoldState', function ($http, $q) {
    return {
        setTypeOfLaw : function (a) { localStorage.setItem('LawType', a) },
        setCourthouse : function (a) { localStorage.setItem('Building', a) },
        setDepartment : function (a) { localStorage.setItem('Dept', a) },
        getTypeOfLaw : function () {
            var LT = localStorage.getItem('LawType');
            return LT;
        },
        getCourthouse : function () {
            var BLDG = localStorage.getItem('Building');
            return BLDG;
        },
        getDepartment : function () {
            var DEPT = localStorage.getItem('Dept');
            return DEPT;
        }
    }
});

答案 2 :(得分:0)

我的猜测是你可以在服务代码中返回this对象:

var StateService = angular.module('StateService', [])
  .service('HoldState', function ($http, $q) {
    this.setTypeOfLaw = function (a) { localStorage.setItem('LawType', a) };
    // add all your other functions and code as well
    return this;  // this is the service that will be injected into the controller
  }

但如果没有完整的服务定义,或者至少足够完整,很难准确地说出你做错了什么。