微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/angularjs/140725.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐