angularjs – 如何拦截$资源请求

有没有办法拦截$资源调用中的请求?

我想添加一个OAUTHv2标头,而不是为每个资源模型指定.

目前我只能拦截回应,如文档中所述:

interceptor – {Object=} – The interceptor object has two optional
methods – response and responseError. Both response and responseError
interceptors get called with http response object. See $http
interceptors.

我知道你可以在$http上推一个全局拦截器,但是我不想在API调用之外的任何请求中包含我的承载令牌(security …)

任何正在做OAUTHv2的人都必须遇到这个问题.可惜在Angular.JS中没有标准的方法

虽然这并不明显,但是有一种方法拦截$资源请求.

这是一个例子:

<!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>

怎么运行的:

> $资源合并动作定义,请求参数和数据构建$http请求的配置参数.
>传递给$http请求的配置参数被视为对象的承诺,因此它可能包含初始化配置的功能.
> Action的功能可以根据需要转换请求.

演示可以在transform-request.html找到

Elsewhere我已经显示了一种类似的方法来取消$资源请求.

参见:Intercept angularjs resource request

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...