gpt4 book ai didi

javascript - 如何在 Angular $resource中使用自定义操作

转载 作者:行者123 更新时间:2023-11-28 01:14:05 25 4
gpt4 key购买 nike

根据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
])

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

enter image description here

<小时/>

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

最佳答案

首先,对于资源,您不能默认帖子正文,因为这会违反 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 所致?尽管这可能有些牵强。您可能需要与管理您的服务器的人员协商。

关于javascript - 如何在 Angular $resource中使用自定义操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24053030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com