如何使用业务逻辑扩展已解析的$资源

How to extend a resolved $resource with business logic

本文关键字:资源 扩展 何使用 业务      更新时间:2023-09-26

我有以下场景

服务:

.factory(
    'itemsApi',
    function($resource) {
        return $resource("/api/items/:id", { id: "@_id" }, {
            'create': { method: 'POST' },
            'get': { method: 'GET', isArray: false },
            'update': { method: 'PUT' }
        });
    })

路由器

$routeProvider
    .when("/item/:id", {
        templateUrl: "item.tpl.html",
        controller: "ItemController",
        resolve: {
           item: ['$route', 'itemsApi', function ( $route, itemsApi) {
                return itemsApi.get({ id: $route.current.params.id });
            }]
        }
    }
})

控制器

.controller('ItemController',['$scope','item', function($scope, item) {
    $scope.item = item;
}

到目前为止一切都很好。我的控制器里有这个项目。现在我想用我的业务逻辑来扩展$scope.item

业务逻辑

function Item() {}
Item.prototype.totalPrice = function() {
   // $scope.item should be here 'this'
   return this.price + this.shipping;
}

目标:

以Angular方式用业务逻辑扩展$scope.item

我试过使用angular.extend,但不起作用$scope.item没有totalPrice函数。

例如:控制器中的

$scope.item = angular.extend(item, new Item());

问题

如何优雅地得到$scope.item包含Item类的方法?


编辑

@ryeballar提出的解决方案产生了丑陋的效果。

现在"$scope.item"将$resource包装在"$scoper.item.item"中

所以我应该更改文档中的每个绑定路径。

发件人

<span ng-bind="item.price"></span>

收件人

<span ng-bind="item.item.price"></span>

这对我来说是不可接受的,感觉很糟糕。然后我想到了这个解决方案

项构造函数

var Item = function Item(item) {
    // mixing
    angular.extend(this, item);
};

这解决了上一个问题,但产生了新的问题。

现在$scope.item不包含$resource方法。(例如$scope.item.update())由于__proto__Resourse更改为Item

最后

虽然CCD_ 12不再具有CCD_ 13和CCD_。则可以使用CCD_ 15。

if ($scope.item._id) {
    itemsApi.update({ id: $scope.item._id}, $scope.item)
            .$promise.then(function(item) {
                    $scope.item = new Indoor(item);                       
            });
} else {
    itemsApi.create($scope.item)
            .$promise.then(function(item) {
                    $scope.item= new Indoor(item);
             });
}

Item模型创建一个工厂服务,并将其注入解析中,然后将解析后的值作为Item对象返回。

项目服务

.factory('Item', function() {
  var Item = function(item) {
    this.item = item;
  };
  Item.prototype.totalPrice = function() {
    return this.item.price + this.item.shipping;
  };
  return Item;
});

路由器

$routeProvider
    .when("/item/:id", {
        templateUrl: "item.tpl.html",
        controller: "ItemController",
        resolve: {
           item: ['$route', 'itemsApi', 'Item', function ( $route, itemsApi, Item) {
                return itemsApi.get({ id: $route.current.params.id })
                  .$promise.then(function(item) {
                    return new Item(item);
                  });
            }]
        }
    }
});

控制器

.controller('ItemController', ['$scope', 'item', function($scope, item) {
  $scope.item = item; // this is an Item Object
}]);

HTML

{{item.totalPrice()}}