使用angular.copy来扩展服务

时间:2022-07-26 21:16:22

I have made baseService in angular as following.

我已经在angular中使用了baseService,如下所示。

app.service('baseService', ['$http', function($http) {

        'use strict';
        this.service = "";
        this.load = function(){
            // implement load 
        }
}]);

Now i want other services to extend this service as the implementation of load method will be same for all the services. My derived service will look as follow.

现在我希望其他服务扩展此服务,因为load方法的实现对于所有服务都是相同的。我的派生服务将如下所示。

app.service('jobsService', ['baseService', function( baseService ){

    'use strict';

    angular.copy(baseService, this);

    this.service = 'jobs';    

}]);

Here I am using angular.copy(baseService, this); to extend the baseService. Is this a right approach to inherit a service?

这里我使用angular.copy(baseService,this);扩展baseService。这是继承服务的正确方法吗?

4 个解决方案

#1


0  

A simpler and fairly straightforward option will be to use John Resig's Simple JavaScript Inheritance class.

一个更简单,相当简单的选择是使用John Resig的Simple JavaScript Inheritance类。

This gives you a more object oriented approach to inheriting/extending classes plus extra functionalities like constructor calls, function overrides etc.

这为您提供了一种更加面向对象的方法来继承/扩展类以及额外的功能,如构造函数调用,函数覆盖等。

Using your example:

使用你的例子:

'use strict';

angular.module('app').factory('BaseService', function ($http) {

  var service = Class.extend({ //Class from John Resig's code
    init: function (params) {
      this.params = params;
    },
    load: function (params) {

      return;
    },

  return service;
});

Then to extend/inherit:

然后扩展/继承:

angular.module('app').factory('JobService', function (BaseService) {

  var service = BaseService.extend({
    init: function (params) {
      this._super(params);
    }
  });

  return new service;
});

#2


1  

Yes... I'd say so.

是的......我会这么说的。

You're approach is fine and I'd agree that this an appropriate solution for this. More of a best practice question rather than specifics. Here is a fully working example with both the service and factory patterns Angular provides for different development preference

你的方法很好,我同意这是一个适当的解决方案。更多的是最佳实践问题,而不是具体细节。这是一个完整的工作示例,包含Angular为不同的开发首选项提供的服务和工厂模式

fiddle

小提琴


angular.module('app', []);

angular.module('app').factory('BaseFactory', [ function() {

    var load = function() {
        console.log('loading factory base');
    }

    return { 'load': load }
}]);

angular.module('app').factory('ChildFactory', ['BaseFactory', function (BaseService) {

  var child = angular.copy(BaseService);

  child.childLoad = function () {
      console.log('loading factory child');
  };

  return child;
}]);

angular.module('app').service('BaseService', [function() {

    this.load = function() {
        console.log('loading service base');
    }
}]);

angular.module('app').service('ChildService', ['BaseService', function(BaseService) {

    angular.copy(BaseService, this);

    this.childLoad = function() {
        console.log('loading service child');
    }
}]);

angular.module('app').controller('ctrl', ['$scope', 'ChildFactory', 'ChildService', function($scope, ChildFactory, ChildService) {

    ChildService.load();       // 'loading service base'
    ChildService.childLoad();  // 'loading service child'
    ChildFactory.load();       // 'loading factory base'
    ChildFactory.childLoad();  // 'loading factory child'
}]);

#3


0  

   var BaseService = (function () {
      var privateVar = 0;
      return {
        someAwesomeStuff: function () {
          if (privateVar === 42) {
            alert('You reached the answer!');
          }
          privateVar += 1;
        };
      };
    }());

And create child service like this:

并创建这样的子服务:

var ChildService = Object.create(BaseService);
ChildService.someMoreAwesomeStuff = function () {
  //body...
};

module.factory('ChildService', function () {
  return ChildService;
});

and you can use this ina controller like this:

你可以在这样的控制器中使用这个:

function MyCtrl(ChildService) {
  ChildService.someAwesomeStuff();
}

reference

参考

#4


0  

Here is your solution (extended2Service), and a solution that i usually use (extendedService).

这是您的解决方案(extended2Service),以及我通常使用的解决方案(extendedService)。

Personally i prefer my solution because i don't made a new istance of that object.

我个人更喜欢我的解决方案,因为我没有对该对象做出新的评价。

angular.module('app',[])
.controller('mainCtrl', ['$scope', 'baseService', 'extendedService', 'extended2Service', function($scope, baseService, extendedService, extended2Service ){
  $scope.test = 8;
                      
  $scope.resultBase = baseService.addOne($scope.test);                       
  $scope.resultExtended = extendedService.sum($scope.test, 10);
  $scope.result2Extended = extended2Service.sum($scope.test, 10);
  
  console.log(extendedService);
  console.log(extended2Service);
}])
.factory('baseService', function(){
  var baseService = {};
  
  var _addOne = function(n) {
    return n+1;
  };
  
  baseService.addOne = _addOne;
  return baseService;
  
})
.factory('extendedService', ['baseService', function(baseService){
  var extendedService = {};
  
  var _sum = function(a, b){
    for (var i = 0; i < b; i++) {
      a = baseService.addOne(a);
    }
    return a;
  };
  
  extendedService.addOne = baseService.addOne;
  extendedService.sum = _sum;
  
  return extendedService;
    
}])
.factory('extended2Service', ['baseService', function(baseService){
  var extended2Service = angular.copy(baseService);
  
  var _sum = function(a, b){
    for (var i = 0; i < b; i++) {
      a = baseService.addOne(a);
    }
    return a;
  };
  extended2Service.sum = _sum;
  
  return extended2Service;
}]);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
<div ng-app="app" ng-controller="mainCtrl">
  Value: {{test}} <br>
  Base: {{resultBase}} <br>

  resultExtended : {{resultExtended}} <br>
  result2Extended: {{result2Extended}}
<div>

#1


0  

A simpler and fairly straightforward option will be to use John Resig's Simple JavaScript Inheritance class.

一个更简单,相当简单的选择是使用John Resig的Simple JavaScript Inheritance类。

This gives you a more object oriented approach to inheriting/extending classes plus extra functionalities like constructor calls, function overrides etc.

这为您提供了一种更加面向对象的方法来继承/扩展类以及额外的功能,如构造函数调用,函数覆盖等。

Using your example:

使用你的例子:

'use strict';

angular.module('app').factory('BaseService', function ($http) {

  var service = Class.extend({ //Class from John Resig's code
    init: function (params) {
      this.params = params;
    },
    load: function (params) {

      return;
    },

  return service;
});

Then to extend/inherit:

然后扩展/继承:

angular.module('app').factory('JobService', function (BaseService) {

  var service = BaseService.extend({
    init: function (params) {
      this._super(params);
    }
  });

  return new service;
});

#2


1  

Yes... I'd say so.

是的......我会这么说的。

You're approach is fine and I'd agree that this an appropriate solution for this. More of a best practice question rather than specifics. Here is a fully working example with both the service and factory patterns Angular provides for different development preference

你的方法很好,我同意这是一个适当的解决方案。更多的是最佳实践问题,而不是具体细节。这是一个完整的工作示例,包含Angular为不同的开发首选项提供的服务和工厂模式

fiddle

小提琴


angular.module('app', []);

angular.module('app').factory('BaseFactory', [ function() {

    var load = function() {
        console.log('loading factory base');
    }

    return { 'load': load }
}]);

angular.module('app').factory('ChildFactory', ['BaseFactory', function (BaseService) {

  var child = angular.copy(BaseService);

  child.childLoad = function () {
      console.log('loading factory child');
  };

  return child;
}]);

angular.module('app').service('BaseService', [function() {

    this.load = function() {
        console.log('loading service base');
    }
}]);

angular.module('app').service('ChildService', ['BaseService', function(BaseService) {

    angular.copy(BaseService, this);

    this.childLoad = function() {
        console.log('loading service child');
    }
}]);

angular.module('app').controller('ctrl', ['$scope', 'ChildFactory', 'ChildService', function($scope, ChildFactory, ChildService) {

    ChildService.load();       // 'loading service base'
    ChildService.childLoad();  // 'loading service child'
    ChildFactory.load();       // 'loading factory base'
    ChildFactory.childLoad();  // 'loading factory child'
}]);

#3


0  

   var BaseService = (function () {
      var privateVar = 0;
      return {
        someAwesomeStuff: function () {
          if (privateVar === 42) {
            alert('You reached the answer!');
          }
          privateVar += 1;
        };
      };
    }());

And create child service like this:

并创建这样的子服务:

var ChildService = Object.create(BaseService);
ChildService.someMoreAwesomeStuff = function () {
  //body...
};

module.factory('ChildService', function () {
  return ChildService;
});

and you can use this ina controller like this:

你可以在这样的控制器中使用这个:

function MyCtrl(ChildService) {
  ChildService.someAwesomeStuff();
}

reference

参考

#4


0  

Here is your solution (extended2Service), and a solution that i usually use (extendedService).

这是您的解决方案(extended2Service),以及我通常使用的解决方案(extendedService)。

Personally i prefer my solution because i don't made a new istance of that object.

我个人更喜欢我的解决方案,因为我没有对该对象做出新的评价。

angular.module('app',[])
.controller('mainCtrl', ['$scope', 'baseService', 'extendedService', 'extended2Service', function($scope, baseService, extendedService, extended2Service ){
  $scope.test = 8;
                      
  $scope.resultBase = baseService.addOne($scope.test);                       
  $scope.resultExtended = extendedService.sum($scope.test, 10);
  $scope.result2Extended = extended2Service.sum($scope.test, 10);
  
  console.log(extendedService);
  console.log(extended2Service);
}])
.factory('baseService', function(){
  var baseService = {};
  
  var _addOne = function(n) {
    return n+1;
  };
  
  baseService.addOne = _addOne;
  return baseService;
  
})
.factory('extendedService', ['baseService', function(baseService){
  var extendedService = {};
  
  var _sum = function(a, b){
    for (var i = 0; i < b; i++) {
      a = baseService.addOne(a);
    }
    return a;
  };
  
  extendedService.addOne = baseService.addOne;
  extendedService.sum = _sum;
  
  return extendedService;
    
}])
.factory('extended2Service', ['baseService', function(baseService){
  var extended2Service = angular.copy(baseService);
  
  var _sum = function(a, b){
    for (var i = 0; i < b; i++) {
      a = baseService.addOne(a);
    }
    return a;
  };
  extended2Service.sum = _sum;
  
  return extended2Service;
}]);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
<div ng-app="app" ng-controller="mainCtrl">
  Value: {{test}} <br>
  Base: {{resultBase}} <br>

  resultExtended : {{resultExtended}} <br>
  result2Extended: {{result2Extended}}
<div>