Angularjs ngResource:向特定项目发出POST请求
我有以下论坛的基本API:Angularjs ngResource:向特定项目发出POST请求,angularjs,rest,angular-resource,ngresource,Angularjs,Rest,Angular Resource,Ngresource,我有以下论坛的基本API: POST/topics(创建新主题) GET/topics(获取所有主题) GET/topics/1(获取ID为“1”的主题) 我想补充以下内容: POST/topics/1(添加ID为“1”的主题回复) 我尝试了以下代码(相关摘录),但没有成功: .controller('TopicReplyController', function ($scope, $routeParams, Topics) { 'use strict'; var to
(创建新主题)POST/topics
(获取所有主题)GET/topics
(获取ID为“1”的主题)GET/topics/1
(添加ID为“1”的主题回复)POST/topics/1
.controller('TopicReplyController', function ($scope, $routeParams, Topics) {
'use strict';
var topicId = Number($routeParams.topicId);
Topics.get({topicId: topicId}, function (res) {
$scope.topic = res;
});
$scope.postReply = function () {
var newPost = new Topics({
topicId: topicId
});
newPost.text = $scope.postText;
newPost.$save(); // Should post to /topics/whatever, not just /topics
};
})
.factory('Topics', function ($resource) {
'use strict';
return $resource('/topics/:topicId', {topicId: '@id'});
});
它只是向/topics
发出请求,但不起作用
有什么办法可以让它工作吗?来自:
如果参数值的前缀为@,则该参数的值将从数据对象中提取(对于非GET操作非常有用)`
您正在指定topicId
将是您正在使用的对象的id
$resource('/topics/:topicId', {topicId: '@id'});
// ^^^^^^^^^^^^^^
// Here is where you are mapping it
您希望传递id:topicId
,以便它将id
映射到URL中的topicId
var newPost = new Topics({
id: topicId
});
是否要更新/topics/1或创建ID为1的新“主题”?我想向ID为1的主题添加新帖子,这需要向/topics/1发送帖子请求。这很不寻常,但还是很舒服。谢谢。这并不是我最终如何做的,相反,我在
$save()
的对象中指定了它作为参数,但稍后我将测试您的是否有效,并将其标记为解决方案(如果有效)。