我看角的通用工廠CRUD(這我目前在超過使用服務的偏好):在Angular中重複使用相同的數據工廠是否可行?
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 Base放在具體的存儲庫中,而不是在控制器中。當然有用,但是想知道是否推薦? – ElHaix
我真的很喜歡這種方法! – beeman
不錯,我在找它! – Sajgoniarz