cla*_*re_ 2 rest put slim angularjs
我是AngularJS的新手,无法通过REST更新对象。我正在使用PHP / Mysql后端(Slim框架)。
我能够检索(GET),创建(POST)一个新对象,但不能编辑(PUT)一个对象。这是代码:
我的表格:
<form name="actionForm" novalidate ng-submit="submitAction();">
Name: <input type="text" ng-model="action.name" name="name" required>
<input type="submit">
</form>
Run Code Online (Sandbox Code Playgroud)
我的服务:
var AppServices = angular.module('AppServices', ['ngResource'])
AppServices.factory('appFactory', function($resource) {
return $resource('/api/main/actions/:actionid', {}, {
'update': { method: 'PUT'},
});
});
Run Code Online (Sandbox Code Playgroud)
app.js
var app = angular.module('app', ['AppServices'])
app.config(function($routeProvider) {
$routeProvider.when('/main/actions', {
templateUrl: 'partials/main.html',
controller: 'ActionListCtrl'
});
$routeProvider.when('/main/actions/:actionid', {
templateUrl: 'partials/main.html',
controller: 'ActionDetailCtrl'
});
$routeProvider.otherwise({redirectTo: '/main/actions'});
});
Run Code Online (Sandbox Code Playgroud)
controllers.js:
function ActionDetailCtrl($scope, $routeParams, appFactory, $location) {
$scope.action = appFactory.get({actionid: $routeParams.actionid});
$scope.addAction = function() {
$location.path("/main/actions/new");
}
$scope.submitAction = function() {
// UPDATE CASE
if ($scope.action.actionid > 0) {
$scope.action = appFactory.update($scope.action);
alert('Action "' + $scope.action.title + '" updated');
} else {
// CREATE CASE
$scope.action = appFactory.save($scope.action);
alert('Action "' + $scope.action.title + '" created');
}
$location.path("/main/actions");
}
}
Run Code Online (Sandbox Code Playgroud)
在Slim的api / index.php中,我定义了以下路由和函数:
$app->get('/main/actions', 'getActions');
$app->get('/main/actions/:actionid', 'getAction');
$app->post('/main/actions', 'addAction');
$app->put('/main/actions/:actionid', 'updateAction');
Run Code Online (Sandbox Code Playgroud)
当我创建一个新的“动作”时,一切都按预期工作。但是,当我尝试编辑现有的时,出现以下错误:
PUT HTTP://project.local/api/main/actions 404未找到
操作未更新(尽管显示警告消息“操作xxx已更新”)
我的routeProvider设置是否有问题?我想PUT网址末尾缺少ID ...
我精确地指出,例如,如果我尝试使用POSTMan-Chrome-Extension模拟PUT请求,则一切运行正常(PUT http://project.local/api/main/actions/3返回预期的数据)
更仔细地阅读之后,问题确实出在执行更新请求时,您没有在URL中发送ID。此外,您调用更新/保存的方式与资源的用途并不完全相同。创建资源后,请在实例上调用save / update方法,而不是将其作为工厂函数。您还可以将实例的属性绑定到url中的参数,因此不必在每次调用时都指定它们:
AppServices.factory('appFactory', function($resource) {
return $resource('/api/main/actions/:actionid', {actionid : '@actionid'}, {
'update': { method: 'PUT'},
});
Run Code Online (Sandbox Code Playgroud)
资源的第二个参数告诉angular应该使用哪些属性来填充url参数。因此get操作保持不变:
$scope.action = appFactory.get({actionid: $routeParams.actionid});
Run Code Online (Sandbox Code Playgroud)
现在是更新:
$scope.submitAction = function() {
// UPDATE CASE
if ($scope.action.actionid > 0) {
$scope.action.$update()
} else {
$scope.action.$save();
}
}
Run Code Online (Sandbox Code Playgroud)
由于您以角型酒窖为基础,所以我可能应该检查一下是否可以改善这一点...
| 归档时间: |
|
| 查看次数: |
9926 次 |
| 最近记录: |