加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS $资源拦截器

发布时间:2020-12-17 07:42:33 所属栏目:安全 来源:网络整理
导读:如何将拦截器添加到$资源调用? 假设我有一个名为Users的资源工厂,就像这样; app.factory('Users',['$resource','resourceInterceptor',function ($resource,resourceInterceptor) { return $resource( 'users/:user_id',{ user_id: '@id' },{ query: { meth
如何将拦截器添加到$资源调用?

假设我有一个名为Users的资源工厂,就像这样;

app.factory('Users',['$resource','resourceInterceptor',function ($resource,resourceInterceptor) {
    return $resource(
      'users/:user_id',{
        user_id: '@id'
      },{
        query: {
          method: 'GET',// Not changing the default method,just adding an interceptor
          interceptor: resourceInterceptor // Is there any better way to do this.. like globally?
        },save: {
          method: 'POST',// Same here
          interceptor: resourceInterceptor // Again...
        },...,// And so on
      }
    );
  }]);

我的resourceInterceptor服务看起来像

app.factory('resourceInterceptor',['$rootScope',function ($rootScope) {
    return {
      request: function () {
        // This function isn't executed at all?
        $rootScope.loading = true;
      },response: function () {
        $rootScope.loading = false;
      },responseError: function () {
        $rootScope.loading = false;
      }
    };
  }]);

首先,请求拦截功能永远不会执行,为什么不执行?

其次,必须将拦截器硬编码到现有的$资源方法是非常乏味的,有没有办法更容易地将拦截器分配给特定的$资源调用,甚至可以为所有$资源调用分配一个拦截器?

要在资源中使用拦截器,您应该:

1 – 制作一个httpInterceptor与你的请求,响应,responseError:

app.factory('myInterceptor',function () {
    //Code
    //return { request:...,});

2 – 在您的应用程序中配置此拦截器:

app.config(['$httpProvider',function ($httpProvider) {
    $httpProvider.interceptors.push('myInterceptor');
}]);

现在,你配置你的httpProvider有一个拦截器,无论你注入$http,你将使用这个提供者,所以你会排除你的请求,响应和响应错误功能.

3 – 在资源中使用它.
由于$资源使用$http,并且您配置了一个httpProvider globaly,您将在使用资源时调用拦截器的func.

第二个问题:
您不能将拦截器设置为具体的$http对象,它们(拦截器)全局设置.

(即使您在模块定??义之前设置拦截器,然后将其删除,则无法知道执行顺序)

如果您不想覆盖每个$资源操作中的拦截器属性(如您在问题中写的),您可以执行什么操作,可以改进拦截器.

app.factory('userLoadingInterceptor',function () {
    //Code
    return {
        request: function(){
            //Check if your are working with a url related with users
            // and if so do things...
        }
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读