2014-06-05 52 views
1

根據docs我可以爲每個資源定義自定義操作。這是REST API資源我感興趣的配置(見postman進口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 
]) 

怪異STU ff發生在這裏..首先,而不是使方法調用'POST'它使用'選項',而不是..進一步..它只使用默認定義中設置的參數(即良好的世界,良好的地址..而不是在scope.address值..我測試是有效的)查看請求的摘要/響應這個鉻devtools截圖:

enter image description here


問題: - 如何使該服務使用我使用時使用的參數嗎? - 我如何指定它將參數作爲後JSON數據..而不是追加到查詢字符串?

回答

1

首先,對於資源,您不能默認帖子正文,因爲它違背了Resource對象的角度範例。 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?雖然這可能是一個延伸。您可能想與管理您的服務器的人進行協商。

+0

Hum ..看起來有很多約定和紅色區域和..我認爲整點是簡化了整個事情..這樣做與原始jQuery的更簡單!有人建議我使用restangular或更低級別的$ http對象,並省去IMO的麻煩 – abbood

+0

它使事情變得更簡單。該慣例是爲了防止您在嘗試發佈到服務器的資源中設置默認參數。它也擺脫了許多鍋爐板代碼,否則你必須使用'$ http'創建。另外,您是否考慮過爲搜索功能發佈POST請求不是很RESTful?如果你有服務器的控制權,你能不能通過你的'/ properties'端點中的地址進行搜索:發佈一個像'Properties.query({address:$ scope.address})'這樣的搜索,生成一個'GET'屬性?地址= [PARAM]'? – Mike

相關問題