如何在 angularjs 中为 CRUD 做基本的 class 概念?
How to do base class concept for CRUD in angularjs?
目前正在 angularJS 做学生项目。因为我需要使用 base class 概念
用于 CRUD 操作。我需要在 class 中创建一个基础 class 包含
创建,读取,更新和删除方法..在整个应用程序中我需要使用基于参数和对象的常用方法将数据保存在相应的位置..
您可以创建仅包含 CRUD
函数的 service
或 factory
,您可以将 service
注入 controller
并传递 arguments
或 object
到特定的服务函数。
已更新以显示示例:
app.factory('baseService', ['$http',
function($http) {
return {
create: function(data) {
return $http.post('/api/..', data);
},
read: function() {
return $http.get('/api/..');
},
update: function() {
return $http.put('/api/..', data);
},
delete: function() {
return $http.delete('/api/..');
}
};
}
]);
app.controller('yourController', ['$scope', 'baseService',
function($scope, baseService) {
baseService.read().then(function(response) {
console.log(response);
}, function(error) {
console.log(error);
})
}
]);
创建服务或工厂来处理您的所有 $http
需求。使用 angular 的 $http
shortcut methods 用于 post
、get
、put
和 delete
,其中 returns 是一个承诺
app.factory('DataService', function($http) {
var create = function() {
return $http.post("/api/...") // returns a promise
};
var read = function() {
return $http.get("/api/...")
};
var update = function() {
return $http.put("/api/...")
};
var delete = function() {
return $http.delete("/api/...")
};
return {
create: create,
read: read,
update: update,
delete: delete
}
});
这可以 re-used 在整个应用程序中是这样的:
app.controller('MyController', function ($scope, DataService){
DataService.read().then(
function(data){
console.log(data)
},
function(error){
console.log(error);
})
});
目前正在 angularJS 做学生项目。因为我需要使用 base class 概念 用于 CRUD 操作。我需要在 class 中创建一个基础 class 包含 创建,读取,更新和删除方法..在整个应用程序中我需要使用基于参数和对象的常用方法将数据保存在相应的位置..
您可以创建仅包含 CRUD
函数的 service
或 factory
,您可以将 service
注入 controller
并传递 arguments
或 object
到特定的服务函数。
已更新以显示示例:
app.factory('baseService', ['$http',
function($http) {
return {
create: function(data) {
return $http.post('/api/..', data);
},
read: function() {
return $http.get('/api/..');
},
update: function() {
return $http.put('/api/..', data);
},
delete: function() {
return $http.delete('/api/..');
}
};
}
]);
app.controller('yourController', ['$scope', 'baseService',
function($scope, baseService) {
baseService.read().then(function(response) {
console.log(response);
}, function(error) {
console.log(error);
})
}
]);
创建服务或工厂来处理您的所有 $http
需求。使用 angular 的 $http
shortcut methods 用于 post
、get
、put
和 delete
,其中 returns 是一个承诺
app.factory('DataService', function($http) {
var create = function() {
return $http.post("/api/...") // returns a promise
};
var read = function() {
return $http.get("/api/...")
};
var update = function() {
return $http.put("/api/...")
};
var delete = function() {
return $http.delete("/api/...")
};
return {
create: create,
read: read,
update: update,
delete: delete
}
});
这可以 re-used 在整个应用程序中是这样的:
app.controller('MyController', function ($scope, DataService){
DataService.read().then(
function(data){
console.log(data)
},
function(error){
console.log(error);
})
});