跟我学AngularJs:Aop拦截实例

前端之家收集整理的这篇文章主要介绍了跟我学AngularJs:Aop拦截实例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

摘要:config配置一般都是用来设置请求参数等,可以认为应用它可对angularjs自带的一些方法进行包装。而AOP,它是面向切面编程,全称是Aspect Oriented Programming,有用过Spring的同学都知道,AOP是一种动态代理机制。是对一些方法进行拦截后处理。然后再接着运行方法。而反应在AngularJS其实也就是对请求进行拦截,然后根据不同的拦截时机,有请求前、请求成功后、请求失败后相就的来做处理。当然,你也可以在其它sericve上加拦截,使用aop与指令结合,可以做很强大的功能

一、AOP拦截实例

现在要做的是拦截每一个ajax请求

首先先写一个serice。

  1. appCommon.factory('addLoadingHttpInterceptor',function ($q,$window,$rootScope) {
  2. $rootScope.ActiveAjaxConectionsWithouthNotifications = 0;
  3. var checker = function(parameters,status){
  4. if(status == "request"){
  5. $rootScope.ActiveAjaxConectionsWithouthNotifications+=1;//每发送一个ajax就+1
  6. $rootScope.loading_view = true;
  7. }
  8. if(status == "response"){
  9. $rootScope.ActiveAjaxConectionsWithouthNotifications-=1;//每返回一个ajax就-1
  10.  
  11. }
  12. if($rootScope.ActiveAjaxConectionsWithouthNotifications<=0){
  13. $rootScope.ActiveAjaxConectionsWithouthNotifications=0;
  14. $rootScope.loading_view = false;
  15. $rootScope.loading_show = false;
  16. }
  17. };
  18. return {
  19. 'request': function(config) {
  20. checker(config,"request");
  21. return config;
  22. },'requestError': function(rejection) {
  23. checker(rejection.config,"request");
  24. return $q.reject(rejection);
  25. },'response': function(response) {
  26. checker(response.config,"response");
  27. return response;
  28. },'responseError': function(rejection) {
  29. checker(rejection.config,"response");
  30. return $q.reject(rejection);
  31. }
  32. };
  33. });

然后在config中配置
  1. appCommon.config(function($httpProvider) {
  2. //AOP增强,用来判断是否显示loading动画
  3. $httpProvider.interceptors.push('addLoadingHttpInterceptor');
  4. });

或者将上面两个合在一起写也可以,类似如下:
  1. module.config(['$httpProvider',function ($httpProvider) {
  2. $httpProvider.interceptors.push(function ($q,$rootScope) {
  3. if ($rootScope.activeCalls == undefined) {
  4. $rootScope.activeCalls = 0;
  5. }
  6.  
  7. return {
  8. request: function (config) {
  9. $rootScope.activeCalls += 1;
  10. return config;
  11. },requestError: function (rejection) {
  12. $rootScope.activeCalls -= 1;
  13. return rejection;
  14. },response: function (response) {
  15. $rootScope.activeCalls -= 1;
  16. return response;
  17. },responseError: function (rejection) {
  18. $rootScope.activeCalls -= 1;
  19. return rejection;
  20. }
  21. };
  22. });
  23. }]);

好了,现在可以看看是否可以:

这是页面加载完成后。


这是页面在请求ajax中:


二、AOP与指令结合做Loading动画

上面的图片看到没,笔者自己写了个Loading的指令,然后每次发送ajax请求时,都会在整个页面加一个遮罩,然后出来如上动画。直到请求结果返回才消失。

猜你在找的Angularjs相关文章