我最近完成了这个技巧。
我将从定义一个普通的Javascript构造函数开始。这不必是有角度的服务。我要做的是,以后,扩展构造函数可以按参数传递任何必要的注入。因此,这将是我的角度服务的基本“类”。在这里,我将公开我希望所有角度服务继承的任何内容。
function ParentService($http) { this.$http = $http;}ParentService.prototype.foo = function () { alert("Hello World");};然后,我将继续使用原型继承定义子构造函数。该构造函数确实将是一个有角度的服务(您可以
$inject在最后使用我告诉您)。
function ChildService($http) { Parent.call(this, $http);}ChildService.prototype = new ParentService();ChildService.prototype.baz = function() { return this.$http.get('/sample/rest/call');}ChildService.$inject = ['$http'];然后,我将在相应的角度模块中注册点菜服务:
var app = angular.module('SampleApp', []);app.service('child', ChildService);最后,在我的控制器中,我将简单地注入我的服务,该服务将是我的ChildService构造函数的一个实例,该实例又扩展了ParentService构造函数:
app.controller('MainCtrl', ['$scope', 'child', function ($scope, child) { child.foo(); //alert("Hello World") var promise = child.bar();}]);您可以在这里看到一个JSFiddle
在ngConf上,Youtube上还有一个有趣的视频,名为“
编写大规模的Angular应用程序”,其中涵盖了这些主题中的一些以及有关角度代码可重用性的其他一些想法。



