下载安卓APP箭头
箭头给我发消息

客服QQ:3315713922

web前端:angular http interceptors 拦截器使用分享

作者: bigbong2505     来源: https://www.cnblogs.com/erming/p/11827359.html点击数:1001发布时间: 2020-03-11 14:23:25

标签: java拦截器服务器

Web开发

  在AOP(Aspect-OrientedProgramming)中拦截器用于在某个方法或字段被访问之前,进行拦截然后在之前或之后加入某些操作。

  拦截器

  在开始创建拦截器之前,一定要了解$q和延期承诺api

  出于全局错误处理,身份验证或请求的任何同步或异步预处理或响应的后处理目的,希望能够在将请求移交给服务器之前拦截请求,并在将请求移交给服务器之前将响应拦截发起这些请求的应用程序代码-拦截器利用promiseapi满足同步和异步预处理的需求。

  拦截器是$httpProvider通过将它们添加到$httpProvider.interceptors数组而向其注册的服务工厂。调用工厂并注入依赖项(如果指定),并返回拦截器。

  有两种拦截器(和两种拒绝拦截器):

  request:拦截器通过httpconfig对象调用。该函数可以自由修改config对象或创建新对象。函数需要config直接返回对象,或者包含config或新config对象的Promise。

  requestError:当先前的拦截器抛出错误或被拒绝解决时,拦截器将被调用。

  response:拦截器通过httpresponse对象调用。该函数可以自由修改response对象或创建新对象。函数需要response直接返回对象,或者作为包含response或新response对象的承诺。

  responseError:当先前的拦截器抛出错误或被拒绝解决时,拦截器将被调用。

  //registertheinterceptorasaservice

  $provide.factory('myHttpInterceptor',function($q,dependency1,dependency2){

  return{

  //optionalmethod

  'request':function(config){

  //dosomethingonsuccess

  returnconfig;

  },

  //optionalmethod

  'requestError':function(rejection){

  //dosomethingonerror

  if(canRecover(rejection)){

  returnresponseOrNewPromise

  }

  return$q.reject(rejection);

  },

  //optionalmethod

  'response':function(response){

  //dosomethingonsuccess

  returnresponse;

  },

  //optionalmethod

  'responseError':function(rejection){

  //dosomethingonerror

  if(canRecover(rejection)){

  returnresponseOrNewPromise

  }

  return$q.reject(rejection);

  }

  };

  });

  $httpProvider.interceptors.push('myHttpInterceptor');

  //alternatively,registertheinterceptorviaananonymousfactory

  $httpProvider.interceptors.push(function($q,dependency1,dependency2){

  return{

  'request':function(config){

  //sameasabove

  },

  'response':function(response){

  //sameasabove

  }

  };

  });

  此处有一个坑,在push时,提示未定义拦截器,因为$httpProvider在config拦截器时,拦截器service还不能找到,

  可以将拦截器service定义在config依赖的模块中使用。

  java里的拦截器是动态拦截Action调用的对象。它提供了一种机制可以使开发者可以定义在一个action执行的前后执行的代码,也可以在一个action执行前阻止其执行,同时也提供了一种可以提取action中可重用部分的方式。

赞(8)
踩(0)
分享到:
上一篇:web前端:ES6.x
华为认证网络工程师 HCIE直播课视频教程