如何从其他模块引用函数定义

时间:2013-08-09 06:45:34

标签: javascript angularjs

如何在角度服务中定义函数,然后在另一个服务的函数中使用函数定义。 我实现如下,但它不起作用。我不想返回一个ParentService实例,只是要将其构造函数定义为PersonService的父类。

感谢您的帮助。

var personModule = angular.module('personModule',['coreModule']).service('personService', function($q, jAjax){

    function PersonService($q, jAjax) {
        var self = this;
        ParentService.call(self, $q, jAjax);
        this.name = "person";
    };

    inherit(ParentService, PersonService);

  PersonService.prototype.loadPersonList = function() {
        var self = this;
        var deferred = self.$q.defer();
        ParentService.prototype.loadList.call(self, "meta", function(data){
            self.items = data;
            deferred.resolve(data);
        });
        return  deferred.promise;
    };

  return new PersonService($q);
});

var coreModule = angular.module('coreModule',[]).service('commonService', function(jAjax){

 var ParentService = function(jAjax) {
 };

 ParentService.prototype.loadList = function(docType, fn) {
    var self = this;
    var url = self.name + "/get";

    self.jAjax.get(url).success(function(data) {
        if (fn !== undefined) {
            fn.call(this, data);
        }
    });
 };

 return ParentService;
});

1 个答案:

答案 0 :(得分:0)

感谢您的时间。我找到了解决方案。在parentService中,我返回一个包含函数定义

的对象
return {ParentService:ParentService};

,然后在其他模块中我将其作为属性

inherit(commonService.ParentService, PersonService);

固定代码在

之下
var personModule = angular.module('personModule',['coreModule']).service('personService', function($q, jAjax, commonService){

function PersonService($q, jAjax, commonService) {
    var self = this;
    ParentService.call(self, $q, jAjax);
    this.name = "person";
};

inherit(commonService.ParentService, PersonService);

PersonService.prototype.loadPersonList = function() {
    var self = this;
    var deferred = self.$q.defer();
    commonService.ParentService.prototype.loadList.call(self, "meta", function(data){
        self.items = data;
        deferred.resolve(data);
    });
    return  deferred.promise;
};

return new PersonService($q, jAjax, commonService);
 });

  //Calling module
 var coreModule = angular.module('coreModule',[]).service('commonService',function(jAjax){

 var ParentService = function(jAjax) {
 };

 ParentService.prototype.loadList = function(docType, fn) {
  var self = this;
  var url = self.name + "/get";

  self.jAjax.get(url).success(function(data) {
     if (fn !== undefined) {
         fn.call(this, data);
     }
    });
  };

  return {ParentService:ParentService};
  });