【发布时间】:2016-04-27 06:04:43
【问题描述】:
我创建了一个带有 CRUD 功能的 Spring 和 AngularJS 的简单应用程序。
现在,包含我传递的数组列表的作用域变量在创建新变量时不会更新。
这是我的 AngularJS 控制器
代码$scope.agency = {id: null, name: '', contact: '', employees: []};
$scope.agencies = [];
$scope.getAllAgencies = function() {
AgencyService.getAllAgencies()
.then(
function (response) {
$scope.agencies = response;
}
)
};
$scope.getAllAgencies();
$scope.createAgency = function(agency) {
AgencyService.createAgency(agency)
.then(
$scope.getAllAgencies(),
function(errReponse){
console.error('Error while creating Agency.');
}
);
};
$scope.submit = function () {
console.log("Saving new Agency");
$scope.createAgency($scope.agency);
$scope.reset();
};
$scope.reset = function(){
$scope.agency = {id: null, name: '', contact: '', employees: null};
$scope.myForm.$setPristine(); //reset Form
};
服务
App.factory('AgencyService', ['$http', '$q', function($http, $q) {
return {
getAllAgencies: function() {
return $http.get('/agency')
.then(
function(response) {
return response.data;
},
function(errResponse){
console.error('Error while fetching agencies');
return $q.reject(errResponse);
}
)
},
createAgency: function(agency) {
console.log("Creating Agency");
return $http.post('/agency', agency)
.then(
function (response) {
return response.data;
},
function (errResponse) {
console.error('Error while create agency');
return $q.reject(errResponse);
}
)
}
};
}]);
这些是我在 Spring 中的方法
获取代理
@RequestMapping(value = "/agency", method = RequestMethod.GET)
public ResponseEntity<List<Agency>> getAllAgencies() {
List<Agency> agencies = agencyService.getAllAgencies();
if (agencies.isEmpty()) {
return new ResponseEntity<List<Agency>>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<List<Agency>>(agencies, HttpStatus.OK);
}
创建代理
@RequestMapping(value = "/agency", method = RequestMethod.POST)
public ResponseEntity<Void> createAgency(@RequestBody Agency agency, UriComponentsBuilder ucBuilder) {
if(agencyService.isAgencyExists(agency)) {
System.out.println("CONFLICT");
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}
agencyService.saveAgency(agency);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/agency/{id}").buildAndExpand(agency.getId()).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
注意:当我调试时,在 post 方法之后它不会继续我的 get 方法。
这没有错误,当我重新加载时,它会得到所有内容,包括我刚刚创建的那个。
谢谢!
【问题讨论】:
-
是不是像新建代理时列表没有更新?
-
没错!那是我的问题。如果您看到我的代码,那应该可以工作。
-
真的必须在createAgency() 之后调用getAllAgencies 吗?你不能在 200 OK 响应后将保存的代理推送到现有数组中吗?
-
我试过了,它成功了,但我想在 createAgency 之后调用 getAllAgencies。我以前也做过这样的事情,我不知道为什么它现在不起作用。这是我的参考websystique.com/springmvc/spring-mvc-4-angularjs-example。 p.s 我正在考虑实时通话,所以这可能是最好的方法。
-
您使用的是哪个浏览器?是IE吗?
标签: java angularjs spring spring-mvc