如何在angular $ resource中使用自定义操作

时间:2014-06-05 06:26:06

标签: javascript html5 angularjs coffeescript

根据docs,我可以为每个资源定义自定义操作。这是我有兴趣配置的REST API资源(请参阅postman import link):

http://0.0.0.0:9000/api/properties_by_address
method: POST
post data: raw json:
{
  "address" : "%address%"
}

在我的服务中设置资源(我称之为搜索,请参阅等效的js):

window.API_HOST ="http://localhost:9000/api/";
angular.module("app.services", [])
.factory("Properties", [
    "$resource"
    ($resource) ->
      $resource API_HOST + "properties/:id", null,
        search:
          method: 'POST'
          url: API_HOST + 'properties_by_address'
          params:
            hello: 'good world'
            address: 'good address'
])

我尝试在这样的指令中调用它(请参阅this进行js转换):

.directive('homeSearch', ['Properties', (properties) ->
    restrict: 'AEC'
    replace: false
    templateUrl: '/partials/home_search.html'
    link: (scope, elem, attrs) ->
      button = elem.find('.button')
      button.bind "click", ->
        console.log "address searched" + scope.address
        properties.search {}, address: scope.address
      return
])

奇怪的东西发生在这里..首先,而不是使mothod调用'POST'它使用'OPTIONS'代替..进一步..它只使用默认定义中设置的参数(即好世界,好地址) ..而不是我测试为有效的scope.address值..请参阅此chrome devtools屏幕截图中的请求/响应摘要:

enter image description here


的问题: - 如何使服务使用我调用时使用的参数? - 我如何指定它将参数作为后JSON数据..而不是将其附加到查询字符串?

1 个答案:

答案 0 :(得分:1)

首先,对于资源,您不能默认帖子正文,因为它会违反Resource对象的Angular范例。 Here's a better answer than I could give。基本上,params属性将始终只默认您的查询字符串参数。

此外,您应该像这样定义您的资源:

// Tell $resource that the 'id' property resides within the resource by using '@id'
$resource(API_HOST+ '/properties/:id', {id: '@id'}, {
  search: {
    url: API_HOST + 'properties_by_address',
    method: 'POST'
  }
});

要更改帖子的请求正文,您必须像这样调用搜索功能:

Properties.search({address: $scope.address, hello: 'good world'}, function(result){
  // Do something with the response here
}, function(error) {/* handle error here if you want*/});

就使用的OPTIONS方法而言,我之前没有看到过。可能是因为您要求的API?虽然这可能是一个延伸。您可能希望与管理服务器的人员进行协商。