AngularJS的设计模式与具有一组公共字段的2个服务一起使用

What AngularJS design pattern to use with 2 services that have a common set of fields?

本文关键字:服务 2个 一起 字段 设计模式 具有一 AngularJS      更新时间:2023-09-26

我遇到的情况是,我提出的每一个解决方案对我来说都不是很"有角度",所以这让我怀疑我是否在某个地方错过了一个明显的方法。我有两个共享一组公共字段的服务(在本例中,分页字段有助于在屏幕上分页数据)-

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个字段还不错,但随着添加了更多的字段和函数,我最终复制了大量代码。如果我只是使用这里的函数,我可以在两者之间共享一个公共服务,但由于我有数据,我不能使用singleton(两个服务都需要在字段中有自己的值)。在像C#这样的OO语言中,我会通过继承来解决这个问题,但在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);