随着AngularJS,我不想设置全局$ http.defaults.headers.common。我可以把我的自定义标题,每个$资源调用? [英] With AngularJS, I don't want to set the global $http.defaults.headers.common. Can I send my custom header with each $resource call?
问题描述
我打电话,我无法控制的后端服务器。目前,它的使用jQuery阿贾克斯这样的:
I'm calling a back-end server that I cannot control. Currently it's using jQuery ajax like this:
return $.ajax({
type: "POST",
url: "/api/cases/store",
contentType: "application/json",
data: JSON.stringify(parameters),
headers: { "Authorization": cred } : {}
}) // ... etc.
我想将其转换为使用 $资源
服务,并得到了它的工作这样做。
I want to convert it to use the $resource
service, and got it working doing this
$http.defaults.headers.common['Authorization'] = cred;
return $resource('/api/cases/store').save();
唯一的问题是,我有与身份验证凭据设置全局 $ HTTP
服务的默认值。
我看到,你应该能够与 $ HTTP
调用自定义页眉传递,现在用 $资源
电话,但我找不到如何做到这一点在我的情况下,任何实例(带POST)。
I am seeing that you're supposed to be able to pass in custom headers with the $http
call, and now with $resource
calls, but I can't find any examples of how to do it in my case (with a POST).
我也找不到AngularJS文档中对这个东西。你们怎么算出这个东西出来?该文档是如此糟糕!
I also can't find anything on this in the AngularJS documentation. How do you guys figure this stuff out? The docs are so bad!
推荐答案
而不是这样的:
$http.defaults.headers.common['Authorization'] = cred;
return $resource('/api/cases/store').save();
做到这一点:
return $resource('/api/cases/store', {}, {
save: {
method: 'POST',
headers: { 'Authorization': cred }
}
}).save();
请注意,您必须使用拯救的行动,在第三个参数中的第一项。无法测试,所以让我知道它是否工作。
Note that you have to use 'save' as the action, the first key in the third parameter. Can't test it, so let me know if it works.
和我同意。文档没有谈论它。看看在DEFAULT_ACTIONS列表在$资源源 - code在角resource.js
And I agree. The documentation doesn't talk about it. Take a look at the DEFAULT_ACTIONS list in the $resource source-code in angular-resource.js
这篇关于随着AngularJS,我不想设置全局$ http.defaults.headers.common。我可以把我的自定义标题,每个$资源调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!