我想映射默认的AngularJS $ resource操作:

  'get':    {method:'GET'}
  'save':   {method:'POST'}
  'query':  {method:'GET', isArray:true}
  'remove': {method:'DELETE'}
  'delete': {method:'DELETE'}

这5条RESTful路线:
  'show':   {method:'GET'}                 -> get
  'create': {method:'POST'}                -> save
  'update': {method:'PUT'}                 -> save
  'index':  {method:'GET', isArray:true}   -> query
  'delete': {method:'DELETE'}              -> remove or delete

除了save之外,其他所有内容都映射良好。它作为create请求在POST上工作。但是我要在保存具有PUT的资源时将其更改为id != null请求
# This factory needs a smarter $save() method
myServices.factory 'Message', ['$resource', ($resource) ->
    Message = $resource "api/users/:user_id/messages/:id",
        user_id: '@user_id'
        id: '@id'
    ,
        # update should not be needed
        update:
            method: 'PUT'

    Message
]


myApp.controller "UsersShowCtrl", ["$scope", "$routeParams", "User", "Message", ($scope, $routeParams, User, Message) ->
    $scope.user = User.get({id: $routeParams.user_id})
    $scope.myMessage = new Message {user_id: $routeParams.user_id}

    $scope.submitMyMessage = ->
        # This should just be:
        # $scope.myMessage.$save()
        # rather than:
        unless $scope.myMessage.id?
            $scope.myMessage.$save()
        else
            $scope.myMessage.$update()

]

我最终还是想修改提交的参数,以便可以将它们命名为默认的Rails嵌套参数,即params[:message],而不是将它们直接附加到根params字符串,但是首先我需要知道如何最好地修改$资源。

最佳答案

我的头顶上,这个save()方法怎么样?

myServices.factory 'Message', ['$resource', ($resource) ->
    Message = $resource "api/users/:user_id/messages/:id",
        user_id: '@user_id'
        id: '@id'
    ,
        # update should not be needed
        update:
            method: 'PUT'

    Message::save = ->
        if @id?
            @update()
        else
            @create()

    Message
]

关于javascript - 扩展AngularJS $ resource以映射到Rails RESTful路线(特别是$ save以创建和更新),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15176185/

10-12 13:51