AngularJS服务存储和更新数据
我有一个简单的应用程序,它显示了一组人,每个人都有一个指向编辑控制器的链接。编辑控制器通过id获取人员。提交编辑表单后,页面将重定向回人员列表 我有一个方法在服务器保存人员后更新回调中的服务数据。我使用的方法确实有效,但是,我不确定是否有更好的方法来实现这一点。经过多次搜索,我还没有找到一个具体的答案,所以我想联系这里的AngularJS社区寻求帮助 这是一把小提琴:AngularJS服务存储和更新数据,angularjs,angularjs-service,Angularjs,Angularjs Service,我有一个简单的应用程序,它显示了一组人,每个人都有一个指向编辑控制器的链接。编辑控制器通过id获取人员。提交编辑表单后,页面将重定向回人员列表 我有一个方法在服务器保存人员后更新回调中的服务数据。我使用的方法确实有效,但是,我不确定是否有更好的方法来实现这一点。经过多次搜索,我还没有找到一个具体的答案,所以我想联系这里的AngularJS社区寻求帮助 这是一把小提琴: var-app=angular.module('peopleApp',[]); app.controller('ListCtrl
var-app=angular.module('peopleApp',[]);
app.controller('ListCtrl',函数($scope,People){
People.getList().then(函数(响应){
$scope.list=response;//显示具有要编辑的新路由链接的人员列表
});
});
app.controller('EditCtrl',函数($scope,$location,$routeParams,People){
//编辑路线,以便按id获取人员
People.getById($routeParams.id)。然后(函数(响应){
$scope.person=response.person;
});
//提交保存人员表单并发送回人员列表
$scope.savePerson=函数(){
People.savePerson($scope.person)。然后(函数(响应){
$location.path('/');
});
}
});
app.factory('People',函数($http,$q){
var people=[];
var people_q=$q.defer();
$http.get(url).then(函数(响应){
人=反应。数据;
人的决心(人);
});
返回{
getList:function(){
回报人民(承诺),;
},
getById:函数(id){
返回$http.get(url).then(函数(响应){
返回响应数据;
});
},
savePerson:函数(person){
返回$http.post(url).then(函数(响应){
//查找person-in-person数组并删除它们
对于(i=0;i
这基本上是我使用过的一种方法,但我会使PeopleService更通用,这样它就可以处理任何对象。另一方面,请确保使用“==”而不是“==”。感谢您在比较中的输入和更正。您可以考虑使用适当的缓存服务(如angular cache)删除您编写的一些代码。这样做的好处是可以在内存/本地存储中进行基于缓存和项目过期的操作——我觉得这很不错。如果您只需要一个服务实例,而不是一个工厂可能返回多个实例,那么我可能会做的唯一区别就是使用一个服务而不是工厂。这两种方法都会奏效,但那将是我要做的唯一改变。
var app = angular.module('peopleApp',[]);
app.controller('ListCtrl',function($scope,People) {
People.getList().then(function(response) {
$scope.list = response; // show list of people with a link to new route to edit
});
});
app.controller('EditCtrl',function($scope,$location,$routeParams,People) {
// edit route so get person by id
People.getById($routeParams.id).then(function(response) {
$scope.person = response.person;
});
// submit save person form and send back to person list
$scope.savePerson = function() {
People.savePerson($scope.person).then(function(response) {
$location.path('/');
});
}
});
app.factory('People',function($http,$q) {
var people = [];
var people_q = $q.defer();
$http.get(url).then(function(response) {
people = response.data;
people_q.resolve(people);
});
return {
getList: function() {
return people_q.promise;
},
getById: function(id) {
return $http.get(url).then(function(response) {
return response.data;
});
},
savePerson: function(person) {
return $http.post(url).then(function(response) {
// find person in person array and remove them
for (i=0; i < people.length; i++) {
if (people[i].person_id == person.person_id) {
people.splice(i,1);
break;
}
}
// add new person data
people.push(response.data);
return response.data;
});
}
}
});