callumacrae
callumacrae

Reputation: 8433

ngResource: Making a POST request to a specific item

I have the following basic API for a forum:

And I want to add the following:

I have tried the following code (relevant excerpt), but it hasn't worked:

.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'});
});

It just makes a request to /topics, which doesn't work.

Any ideas how I can get this to work?

Upvotes: 0

Views: 102

Answers (1)

TheSharpieOne
TheSharpieOne

Reputation: 25726

From the $resource docs:

If the parameter value is prefixed with @ then the value of that parameter is extracted from the data object (useful for non-GET operations).`

You are specifying that the topicId will be the id of the object you are using.

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

You want to pass id: topicId so that it will map id to topicId in the URL.

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

Upvotes: 1

Related Questions