另一个 ngResource 助手的例子。这依赖于绝大多数服务都是这样的事实:
http://host/api/posts
http://host/api/posts/123
http://host/api/posts/123/comments
http://host/api/posts/123/comments/456
因此,任务是创建一个帮助器来创建映射到此类服务的 AngularJS 资源对象。这里是:
'use strict';
var api = angular.module('api', ['ngResource']);
// RESTful API helper
api.addService = function (serviceNameComponents) {
var serviceName = "";
var resource = "/api"; // Root for REST services
var params = {};
serviceNameComponents.forEach(function (serviceNameComponent) {
serviceName += serviceNameComponent;
var lowerCaseServiceNameComponent = serviceNameComponent.toLowerCase();
var collection = lowerCaseServiceNameComponent + 's';
var id = lowerCaseServiceNameComponent + 'Id';
resource += "/" + collection + "/:" + id;
params[id] = '@' + id;
});
this.factory(serviceName, ['$resource',
function ($resource) {
return $resource(resource, {}, {
query: {
method: 'GET',
params: params,
isArray: true
},
save: {
method: 'POST',
},
update: {
method: 'PUT',
params: params,
},
remove: {
method: 'DELETE',
params: params,
}
}
);
}
]);
}
所以,要使用它,只需调用这个助手
api.addService(["Post"]);
api.addService(["Post", "Comment"]);
然后您可以在代码中使用 Post 和 PostComment 以及所需的参数,例如 :post_id