我遇到了一种情况,我似乎想出的每个解决方案对我来说都不太“有 Angular ”,所以这让我想知道我是否在某个地方错过了一个明显的方法。我有两个共享一组通用字段的服务(在本例中,分页字段有助于在屏幕上分页数据)-
app.service('service1', [function () {
var model = this;
model.totalItems = 0;
model.currentPage = 1;
model.itemsPerPage = 10;
}
app.service('service2', [function () {
var model = this;
model.totalItems = 0;
model.currentPage = 1;
model.itemsPerPage = 10;
}
对于只有 3 个字段的情况来说,这还不算太糟糕,但是当我添加了更多字段和函数时,我最终会复制大量代码。如果我只是在这里使用函数,我可以在两者之间共享一个公共(public)服务,但由于我有数据,所以我不能使用单例(两个服务都需要在字段中拥有自己的值)。在像 C# 这样的面向对象语言中,我会通过继承来解决这个问题,但在 JS/Angular 世界中,这似乎不受欢迎,因为它与服务紧密耦合。有人有我缺少的方法吗?
最佳答案
如果您觉得继承是建模的最佳方式,那么不要让 Angular/JavaScript 阻止您使用它。您可以在 Angular 中进行如下设置:
var ParentService = function() {
this.totalItems = 0;
this.currentPage = 1;
this.itemsPerPage = 10;
}
var Service1 = function() {
ParentService.call(this);
}
Service1.prototype = Object.create(ParentService.prototype);
app.service('service1', Service1);
var Service2 = function() {
ParentService.call(this);
}
Service2.prototype = Object.create(ParentService.prototype);
app.service('service2', Service2);
如果组合看起来更合适,您可以使用它。例如:
var ItemPageModel = function() {
this.totalItems = 0;
this.currentPage = 1;
this.itemsPerPage = 10;
}
app.controller('itemPageModel', ItemPageModel);
var Service1 = function($controller) {
this.model = $controller('itemPageModel');
}
Service1.$inject = ['$controller'];
app.service('service1', Service1);
var Service2 = function($controller) {
this.model = $controller('itemPageModel');
}
Service2.$inject = ['$controller'];
app.service('service2', Service2);
关于javascript - 什么 AngularJS 设计模式可以与具有一组公共(public)字段的 2 个服务一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25513306/