我正在研究Angular的通用CRUD工厂(目前我更喜欢使用它而不是服务):
app.factory('dataFactory', ['$http', function ($http) {
var urlBase = '/odata/ContentTypes';
// The _object_ defined in the factory is returned to the caller, rather than as with a service,
// where the _function_ defined in the service is returned to the caller
var dataFactory = {};
dataFactory.getContentTypes = function () {
var contentTypes = $http.get(urlBase);
return contentTypes;
};
dataFactory.getContentType = function (id) {
return $http.get(urlBase + '/' + id);
};
dataFactory.insertContentType = function (contentType) {
return $http.post(urlBase, contentType);
};
dataFactory.updateContentType = function (contentType) {
return $http.put(urlBase + '/' + contentType.ID, contentType);
}
dataFactory.deleteContentType = function (id) {
return $http.delete(urlBase + '/' + id);
}
// to traverse navigation properties
//dataFactory.getUserFromContentTypeId = function (id) {
// return $http.get(urlBase + '/' + id + '/user');
//}
//dataFactory.getOrders = function (id) {
// return $http.get(urlBase + '/' + id + '/orders');
//};
return dataFactory;
}]);
对于我所有的实体,这段代码大致相同。是否可能注入实体名称(或相应的RESTful路径),如果可以,是否可以像部分类一样处理,如果需要其他承诺(如遍历导航属性),它们也可以被注入?
如果使用Angular可以做到这一点,有人能发布一些示例吗?
$http
进行了简单的重构,以后可能会更改...一步一步来。我将OData URL基础放在具体存储库中,而不是控制器中。当然它能工作,但想知道是否推荐这样做? - ElHaix