跟我学AngularJs:Aop拦截实例

来源:互联网 发布:大数据前沿技术及应用 编辑:程序博客网 时间:2024/04/30 06:39

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

一、AOP拦截实例

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

首先先写一个serice。

appCommon.factory('addLoadingHttpInterceptor', function ($q, $window,$rootScope) {    $rootScope.ActiveAjaxConectionsWithouthNotifications = 0;    var checker = function(parameters,status){            if(status == "request"){                $rootScope.ActiveAjaxConectionsWithouthNotifications+=1;//每发送一个ajax就+1                $rootScope.loading_view = true;            }            if(status == "response"){                $rootScope.ActiveAjaxConectionsWithouthNotifications-=1;//每返回一个ajax就-1            }            if($rootScope.ActiveAjaxConectionsWithouthNotifications<=0){                $rootScope.ActiveAjaxConectionsWithouthNotifications=0;                $rootScope.loading_view = false;                $rootScope.loading_show = false;            }    };    return {    'request': function(config) {        checker(config,"request");        return config;    },   'requestError': function(rejection) {       checker(rejection.config,"request");      return $q.reject(rejection);    },    'response': function(response) {         checker(response.config,"response");      return response;    },   'responseError': function(rejection) {        checker(rejection.config,"response");      return $q.reject(rejection);    }  };});

然后在config中配置

appCommon.config(function($httpProvider) {//AOP增强,用来判断是否显示loading动画$httpProvider.interceptors.push('addLoadingHttpInterceptor');});

或者将上面两个合在一起写也可以,类似如下:

module.config(['$httpProvider', function ($httpProvider) {    $httpProvider.interceptors.push(function ($q, $rootScope) {        if ($rootScope.activeCalls == undefined) {            $rootScope.activeCalls = 0;        }        return {            request: function (config) {                $rootScope.activeCalls += 1;                return config;            },            requestError: function (rejection) {                $rootScope.activeCalls -= 1;                return rejection;            },            response: function (response) {                $rootScope.activeCalls -= 1;                return response;            },            responseError: function (rejection) {                $rootScope.activeCalls -= 1;                return rejection;            }        };    });}]);

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

这是页面加载完成后。


这是页面在请求ajax中:


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

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



0 0
原创粉丝点击