是否有一种方法来拦截$resource调用中的请求?
我想向它添加一个OAUTHv2头,而不是为每个资源模型指定它。
目前,我只能拦截响应,如docs中所述:
..。 拦截器- {Object=} -拦截器对象有两个可选的方法-响应和responseError。响应和responseError拦截器都会被http响应对象调用。见$http拦截器。
我知道您可以在$http上推送全局拦截器,但是我不想在API调用之外的任何请求中包含我的Bearer令牌(安全性.)
任何正在做OAUTHv2的人一定遇到过这个问题。很遗憾,在Angular.JS中没有标准的方法.
发布于 2015-05-07 11:19:38
不过,这并不明显,但有一种方法可以拦截$resource请求。
下面是一个示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Intercept resource request</title>
<style type="text/css">.ng-cloak { display: none; }</style>
<script src="angular.js"></script>
<script src="angular-resource.js"></script>
<script>
angular.module("app", ["ngResource"]).
factory(
"services",
["$resource", function ($resource)
{
return $resource(
"http://md5.jsontest.com/",
{},
{
MD5:
{
method: "GET",
params: { text: null },
then: function(resolve)
{
this.params.text = "***" + this.params.text + "***";
this.then = null;
resolve(this);
}
}
});
}]).
controller(
"Test",
["services", function (services)
{
this.value = "Sample text";
this.call = function()
{
this.result = services.MD5({ text: this.value });
}
}]);
</script>
</head>
<body ng-app="app" ng-controller="Test as test">
<label>Text: <input type="text" ng-model="test.value" /></label>
<input type="button" value="call" ng-click="test.call()"/>
<div ng-bind="test.result.md5"></div>
</body>
</html> 它的工作原理:
该演示可在transform-request.html上找到
其他地方我已经展示了一种用于取消$resource请求的类似方法。
发布于 2014-06-06 13:11:02
您可以使用$http拦截器
您可以在$resource方法的选项中传递它们。
关于这方面的文章:http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/
https://stackoverflow.com/questions/24082468
复制相似问题