【发布时间】:2013-07-13 01:50:39
【问题描述】:
我是 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>
我的服务:
var AppServices = angular.module('AppServices', ['ngResource'])
AppServices.factory('appFactory', function($resource) {
return $resource('/api/main/actions/:actionid', {}, {
'update': { method: 'PUT'},
});
});
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'});
});
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");
}
}
在 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');
当我创建一个新的“动作”时,一切都按预期工作。但是当我尝试编辑现有的时,我得到了这个错误:
PUT http://project.local/api/main/actions 404 未找到
动作没有更新(虽然显示了“动作xxx更新”的提示信息)
我的 routeProvider 设置有问题吗?我猜 PUT url 错过了最后的 id...
如果我尝试使用 POSTMan-Chrome-Extension 模拟 PUT 请求,一切正常(PUT http://project.local/api/main/actions/3 返回预期数据)
【问题讨论】:
-
您的代码中的 url 至少不匹配:在资源定义中,您的 url 是 '/api/main/actions/:actionid',但您的调用显示 app/main/ ...。并且警报消息应该放在资源的成功回调中。如果你把它放在它后面,它和 xhr 请求之间就没有逻辑联系。
-
@Narretz,你是正确的成功回调,感谢提示。但是,我的 url 对我来说似乎是正确的:我的 php 后端(slim 框架)位于 /api 下(路由在 /api/index.php 中定义),而网站位于 /app 下。这个架构的灵感来自github.com/Narretz/angular-cellar
-
有趣的是,地窖仍然很受欢迎。 ;) 好吧,这真的很难从远处调试,但是资源中的 url 和您粘贴的返回 404 的 url 之间仍然存在差异,特别是第一个说 api 和第二个 app,即xhr请求在app文件夹中寻找服务器。如果不是拼写错误,那么问题一定出在某个地方。
-
天哪! @Narretz,我什至没有意识到这是您的 github 帐户 :) 我必须再次道歉,因为确实有一个 TYPO:我得到的错误是“PUT project.local/api/main/actions 404 Not Found”(我已经编辑了相应的问题)