我无法弄清楚如何使用$ resource来POST数据来创建新用户。 GET和DELETE工作正常。我花了很长时间在网上尝试不同的方式,但仍然无法实现它们。任何人都可以建议出路吗?
这是我的HTML表单
<input type="text" ng-model="customer.first_name" placeholder="Name">
<input type="text" ng-model="customer.gender" placeholder="Gender">
<input type="number" ng-model="customer.phone_primary" placeholder="Phone Number">
<button type="submit" class="btn btn-primary" ng-click="createCustomer()"> Submit</button>
这是service.js代码
.factory('CustomersFactory', ['$resource', function($resource) {
return $resource('http://localhost:8000/pos/customers/:id', {id: '@id'}, {
update: {method: 'POST'}
});
})];
最后这里是controller.js
.controller('CustomerCtrl', ['$scope','$http', '$location','$resource','CustomersFactory',
function($scope, $http, $location, $resource, CustomersFactory) {
//Get the list of all customers - working fine
$scope.customerList = CustomersFactory.query();
//Delete a user with given customerId - working fine
$scope.deleteCustomer = function (customerId) {
CustomersFactory.delete({ id: customerId });
$scope.customerList = CustomersFactory.query();
};
//And here's the one for posting data which is not working
$scope.createCustomer = function() {
CustomersFactory.update($scope.customer,function(data) {
$scope.customerList.push(data);
});
这是我在控制台上得到的回复 -
'POST localhost:8000 / pos / customers 500(INTERNAL SERVER ERROR)'
当我使用$ http createCustomer方法而不是$ resource时,代码运行正常。这是代码
$scope.createCustomer = function (customer) {
$http.post('http://localhost:8000/pos/customers/',customer); }
答案 0 :(得分:0)
$ resource有方法'save',它通过'POST'htt方法
保存数据.factory('CustomersFactory', ['$resource', function($resource) {
return $resource('http://localhost:8000/pos/customers');
}]);
比你的控制器
.controller('CustomerCtrl', ['$scope','$http', '$location','$resource','CustomersFactory',
function($scope, $http, $location, $resource, CustomersFactory) {
CustomersFactory.save({customer: $scope.customer}, function(data) {
$scope.customerList.push(data);
})
}
您的服务器应该在发布的字段'customer'
中反序列化json对象