angularjs – 如何拦截$资源请求
有没有办法拦截$资源调用中的请求?
我想添加一个OAUTHv2标头,而不是为每个资源模型指定. 目前我只能拦截回应,如文档中所述:
我知道你可以在$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请求的配置参数. 演示可以在transform-request.html找到 Elsewhere我已经显示了一种类似的方法来取消$资源请求. 参见:Intercept angularjs resource request (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |