Jar*_*ves 6 javascript oop inheritance angularjs angular-services
我有一个基类,我想在服务中扩展,以帮助将数据输入到角度范围.我在网上寻找解决方案,但没有找到我喜欢的解决方案.我有一个基类,用于访问设备的文件系统
班级结构:
var cOfflineStorageBase = Class.extend({
init: function(){
},
CreateFolderDir: function(){
},
DeleteAll: function(){
},
DeleteDirectories: function(){
},
DeleteItem: function(){
},
GetFiles: function(){
},
FileExists: function(){
},
GetPath: function(){
},
GetObject: function(){
},
SaveObject: function(){
},
});
Run Code Online (Sandbox Code Playgroud)
我希望能够在几个不同的角度服务(即offlineCart,offlineCustomLists等)中扩展此类,其中每个服务都能够使用存储库来存储各种不同的数据类型.我正在寻找最好,最合适的方式来做角度.在vanilla JavaScript中,你可以这样做:
var newClass = cOfflineStorageBase.extend({
//add new stuff here
});
Run Code Online (Sandbox Code Playgroud)
但我想以棱角分明的方式做同样的事情.
我一直在考虑的方法是使用angular.extend功能,但我不确定这是否合适,或者这样的事情是更合适的方法:
app.factory('someChild', ['$http' , 'cOfflineStorageBase',
function($http, cOfflineStorageBase){
var SomeClass = cOfflineStorageBase.extend({
init: function(){
this._super.init()
},
//Add more stuff here
});
return SomeClass;
}]);
Run Code Online (Sandbox Code Playgroud)
如果这些方法是正确的,或者如果可能有另一个对我想要完成的事情更好,我想要一些建议.我还想或者更愿意在大部分代码中使用promises,因为它会是异步的.
我最近推出了这个技巧.
我将从定义一个纯JavaScript构造函数开始.这不需要是角度服务.我所做的是,后来,扩展构造函数可以通过参数传递任何必要的注入.所以,这将是我的角度服务的基础"类".这是我要暴露任何我希望所有角度服务继承的地方.
function ParentService($http) {
this.$http = $http;
}
ParentService.prototype.foo = function () {
alert("Hello World");
};
Run Code Online (Sandbox Code Playgroud)
然后我将继续使用原型继承来定义子构造函数.这个构造函数确实是一个有角度的服务(你可以告诉我最后的用法$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'];
Run Code Online (Sandbox Code Playgroud)
然后我将在相应的角度模块中注册点菜服务:
var app = angular.module('SampleApp', []);
app.service('child', ChildService);
Run Code Online (Sandbox Code Playgroud)
最后,在我的控制器中,我将简单地注入我的服务,这将是我的ChildService构造函数的一个实例,它反过来扩展了我的ParentService构造函数:
app.controller('MainCtrl', ['$scope', 'child', function ($scope, child) {
child.foo(); //alert("Hello World")
var promise = child.bar();
}]);
Run Code Online (Sandbox Code Playgroud)
你可以在这里看到一个JSFiddle
还有一个有趣的视频在Youtube上来自ngConf,名为Writing A Massive Angular App,它涵盖了一些主题和一些关于角度代码可重用性的其他想法.