我的旧项目中有一段API的代码:
.factory('Api', ['$resource', 'apiUrl', function ($resource, api) {
var Api = $resource(api + ':path', {
path: '@path'
});
return Api;
}])
然后我有一个 Order 模型,它扩展了这个工厂类:
.factory('Order', ['$filter', 'Api', function ($filter, api) {
var Order = api;
angular.extend(Order.prototype, {
getDescription: function () {
var rolls = 0,
cuts = 0,
skus = [],
lines = $filter('orderBy')(this.lines, 'sku');
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
switch (line.type) {
case 0: // cut
cuts++;
break;
case 1: // roll
rolls++
break;
}
if (skus.indexOf(line.sku) == -1) {
skus.push(line.sku);
}
}
var description = '';
description += cuts > 0 ? cuts > 1 ? cuts + ' x cuts' : cuts + ' x cut' : '';
description += rolls > 0 && description.length > 0 ? ', ' : '';
description += rolls > 0 ? rolls > 1 ? rolls + ' x rolls' : rolls + ' x roll' : '';
description += skus.length == 1 ? ' of ' + skus[0] : '';
return description;
},
getStatus: function () {
var lines = this.lines,
status = lines[0].status;
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (status !== line.status)
return 'Multiple';
}
return status;
},
getDeliveryDate: function () {
var lines = this.lines,
date = lines[0].dates.delivery;
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (date !== line.dates.delivery)
return 'Multiple';
}
date = new Date(date);
return date;
},
getDispatchDate: function () {
var lines = this.lines,
date = lines[0].orderDate;
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (date !== lines.orderDate)
return 'Multiple';
}
date = new Date(date);
return date;
}
});
return Order;
}]);
现在,我最近将我的API工厂改为:
// ---
// CONSTANTS.
// ---
.constant('apiUrl', 'http://localhost:54326/')
//.constant('apiUrl', 'http://localhost:81/')
// ---
// SERVICES.
// ---
.service('Api', ['$http', 'HttpHandler', 'apiUrl', function ($http, handler, apiUrl) {
// Private function to build our request
var buildRequest = function (url, method, data, params) {
var model = {
method: method,
url: apiUrl + url,
data: data,
params: params
};
return $http(model);
}
// GET
this.get = function (url, params) {
return handler.loadData(buildRequest(url, 'GET', null, params));
}
// POST
this.post = function (url, data) {
return handler.loadData(buildRequest(url, 'POST', data));
}
// PUT
this.put = function (url, data) {
return handler.loadData(buildRequest(url, 'PUT', data));
}
// DELETE
this.delete = function (url, data) {
return handler.loadData(buildRequest(url, 'DELETE', data));
}
}])
当我这样做时,我的订单模式不再有效。我收到一个错误说明:
无法读取未定义的属性'$$ hashKey'
有没有办法让我的订单模型使用新的API工厂?具体来说,我想附加API返回的每个对象的函数。