2014-01-28 33 views
0

我有一個論壇下面的基本API:ngResource:製作一個POST請求的特定項目

  • POST /topics(創建新主題)
  • GET /topics(得到所有主題)
  • GET /topics/1(送ID爲 「1」 主題)

而且我想補充以下內容:

  • POST /topics/1(添加回復話題ID 「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,這不起作用。

任何想法,我可以得到這個工作?

+0

要更新/主題/ 1還是創建一個ID爲1的新「主題」? – Adrian

+0

我想爲ID爲1的主題添加一個新帖子,該帖子要求向/ topics/1發送POST請求。這是不尋常的,但它仍然是RESTful。 – callumacrae

回答

1

$resource docs

如果參數值的前綴@然後該參數的值是從數據對象中提取(用於有用的非GET操作).`

您指定topicId將是您使用的對象的id

$resource('/topics/:topicId', {topicId: '@id'}); 
          // ^^^^^^^^^^^^^^ 
          // Here is where you are mapping it 

你想傳遞id: topicId,使其在URL映射到idtopicId

var newPost = new Topics({ 
    id: topicId 
}); 
+0

謝謝。這不是我怎麼最終做到的 - 相反,我在'。save()'中將它指定爲一個參數,但是我會測試你的工作是否稍後工作,並將其標記爲解決方案if它也可以工作。 – callumacrae