我正在使用angular js和spring mvc开发一个Web应用程序。
它正在调用spring mvc rest服务并将数据传递给angular js服务,但我无法在服务中看到相同的数据。
controllers.js
app.controller('CustomersController', function($scope, customersService){
init();
function init(){
var data =customersService.getCustomers();
$scope.customers = data;
}
$scope.insertCustomer = function(){
var firstName = $scope.newCustomer.firstName;
var lastName = $scope.newCustomer.lastName;
var city = $scope.newCustomer.city;
customersService.insertCustomer(firstName, lastName, city);
$scope.newCustomer.firstName = '';
$scope.newCustomer.lastName = '';
$scope.newCustomer.city = '';
};
$scope.deleteCustomer = function(id){
customersService.deleteCustomer(id);
};
});
app.controller('NavbarController', function ($scope, $location) {
$scope.getClass = function (path) {
if ($location.path().substr(0, path.length) == path) {
return true;
} else {
return false;
}
};
});
customersService.js
app.service('customersService', function($http, $log) {
this.getCustomers = function() {
$http({
method : 'POST',
url : '/CustomerManagementApp/customers/all'
}).success(function(data, status, headers, config) {
$log.log('Done');
angular.forEach(data, function(c) {
$log.log(c.firstName);
});
customers = data;
return customers;
});
};
this.insertCustomer = function(firstName, lastName, city) {
var topID = customers.length + 1;
customers.push({
id : topID,
firstName : firstName,
lastName : lastName,
city : city
});
};
this.getCustomer = function(id) {
};
this.deleteCustomer = function(id) {
};
var customers = {};
});
我能够在服务中使用forEach循环打印所有数据。但是在控制器中,它显示为空对象数组Object { }。
Firebug控制台没有错误。我正在使用POST方法。如果需要其他代码,请告诉我。
this.getCustomers
改为返回一个 Promise,并在init()
中使用.then
进行链式调用。 - zs2020