AngularJS AOP 实例
AngularJS有种机制叫做拦截器(interceptor),它是$http扩展点,类似ASP.NET MVC的过滤器filter机制,对每个$http请求的发送和接收过程进行过滤。
  $httpProvider 中有一个 interceptors 数组,定义一个工厂服务,并添加到该数组中。
 module.config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push('myInterceptor');
  }]);
定义factory,返回一个对象,有属性request,requestError,response,responseError属性,对每个请求及其进行统一处理,对每次请求都添加上身份认证信息,构造附加的请求地址前缀等,对响应如果有错误或异常,进行统一处理,或弹出对话框。
module.factory('myInterceptor',
['$q', '$log', '$injector', 'loginContext', 'eventAggregator', 'maintainUtil',
function ($q, $log, $injector, loginContext, eventAggregator, maintainUtil) {
    'use strict';
    var apiToken = loginContext.apiToken;
    var tokenType = loginContext.tokenType;
    var webApiHostUrl = loginContext.apiHost + "/api/v1";
    return {
        //token save to services for further usage
        tokenType: tokenType,
        apiToken: apiToken,
        webApiHostUrl: webApiHostUrl,
        // On request success
        request: function (config) {
            if (config.isWebApiRequest && !config.isPlugin) {
                config.url = (config.mkApiUrl || webApiHostUrl) + config.url;
                config.headers = config.headers || {};
                config.headers.Authorization = tokenType + ' ' + (config.mkToken || apiToken);
                var specificOfficeId = Mres.specificOfficeUtil.getOfficeId();
                if (specificOfficeId) {
                    config.headers["specific-office-id"] = specificOfficeId;
                }
            } else if (config.handleApiRequest) {
                config = config.handleApiRequest(config);
            }
            return config;
        },
        // On request failure
        requestError: function (rejection) {
            $log.error(rejection); // Contains the data about the error on the request.
            // Return the promise rejection.
            return $q.reject(rejection);
        },
        // On response failture
        responseError: function (response) {
            $log.error(response); // Contains the data about the error.
            if (response.status === 401) {
                //window.location = '/logoff';
                Mres.logOff();
            } else if (response.data) {
                if (response.data.name == 'MenantInactiveException') {
                    aresMaintainUtil.goToMenantInactivePage();
                }
                eventAggregator.publish(eventAggregator.events.ApiErrorHappened, response, 'myInterceptor');
            } else if (response.status === 0) {
                var isSaasApi = true;
                if (response.config && response.config.url.indexOf('//marketcenter') > -1) {
                    isSaasApi = false;
                }
                if (isSaasApi) {
                    aresMaintainUtil.ensureInMaintainMode().then(function (isInMaintainMode) {
                        if (isInMaintainMode) {
                            mresMaintainUtil.goToMaintainPage();
                        }
                    });
                }
            }
            // Return the promise rejection.
            return $q.reject(response);
        }
    };
}])
适用于对每次请求和响应附加统一功能或数据。
AngularJS AOP 实例的更多相关文章
- angularjs directive 实例 详解
		
前面提到了angularjs的factory,service,provider,这个可以理解成php的model,这种model是不带html的,今天所说的directive,也可以理解成php的mo ...
 - Spring学习笔记IOC与AOP实例
		
Spring框架核心由两部分组成: 第一部分是反向控制(IOC),也叫依赖注入(DI); 控制反转(依赖注入)的主要内容是指:只描述程序中对象的被创建方式但不显示的创建对象.在以XML语言描述的配置文 ...
 - Spring Aop实例@Aspect、@Before、@AfterReturning@Around 注解方式配置
		
用过spring框架进行开发的人,多多少少会使用过它的AOP功能,都知道有@Before.@Around和@After等advice.最近,为了实现项目中的输出日志和权限控制这两个需求,我也使用到了A ...
 - 第一个AngularJS表达式实例
		
<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content=&q ...
 - Spring AOP实例——异常处理和记录程序执行时间
		
实例简介: 这个实例主要用于在一个系统的所有方法执行过程中出线异常时,把异常信息都记录下来,另外记录每个方法的执行时间. 用两个业务逻辑来说明上述功能,这两个业务逻辑首先使用Spring AOP的自动 ...
 - Spring Boot1.5.4 AOP实例
		
原文:https://github.com/x113773/testall/issues/12 1. 还是首先添加依赖(使用当前springboot的默认版本)```<dependency> ...
 - Java框架spring 学习笔记(十二):aop实例操作
		
使用aop需要在网上下载两个jar包: aopalliance.jar aspectjweaver.jar 为idea添加jar包,快捷键ctrl+shift+alt+s,打开添加jar包的对话框,将 ...
 - AngularJS:实例
		
ylbtech-AngularJS:实例 1.返回顶部 1. AngularJS 实例 实例 您可以在线编辑实例,然后点击按钮查看结果. AngularJS 实例 <div ng-app=&qu ...
 - Spring学习十四----------Spring AOP实例
		
© 版权声明:本文为博主原创文章,转载请注明出处 实例 1.项目结构 2.pom.xml <project xmlns="http://maven.apache.org/POM/4.0 ...
 
随机推荐
- Fastdfs 上传图片
			
一.fastdfs-client的jar包导入 1.下载地址:https://github.com/happyfish100/fastdfs-client-java 2.将代码使用git下载下来之后, ...
 - qRT-PCR 注意事项
			
师姐呕心沥血整理的 qRT-PCR 注意事项 关键词: qRT-PCR 注意事项2017-07-17 10:17 来源:生物学霸 点击次数:1257 大家都在说 qRT-PCR 实验原理.引物设计.结 ...
 - [翻译]Javaslang 介绍
			
原文地址:Introduction to Javaslang 1. 概述 在这篇文章中,我们将会探讨: Javaslang 是什么? 为什么需要它? 以及怎样在项目中使用它? Javaslang 是J ...
 - UI设计教程:如何在设计中运用颜色
			
灰度优先 我们习惯在设计阶段的早期就开始调整颜色和色调.但是,当你意识到自己花了3个小时来调整主色调的时候,你发现这种行为毫无帮助.虽然把玩颜色很有吸引力,但是你应该避免在设计初期进行这种行为. 相反 ...
 - autohotkey快捷键
			
;已经基本修复了输入带shift的时候跟输入法中英文切换之间的冲突 SetStoreCapslockMode, off SetKeyDelay, ^CapsLock:: #UseHook ;用这个和下 ...
 - 基于注解的接口限流+统一session认证
			
代码心得: 一个基本的做法:对于用户身份认证做到拦截器里,针对HandlerMethod进行统一拦截认证,根据方法上的注解标识,判别是否需要身份验证,并将查找出来的User实体存入ThreadLoca ...
 - 【Apache】Apache服务的基本概念(二)
			
Apache服务的基本概念 Apache安装请参照:[Apache]Apache服务的安装(一) 1.端口 apache默认监听TCP协议端口80端口 2.apache服务 apache服务默认会启动 ...
 - TCP与UDP传输协议
			
目录结构: contents structure [-] 1 TCP协议和UDP协议的比较 1.1 TCP协议 TCP的全称是Transmission Control Protocol (传输控制协议 ...
 - 导入mysql报错问题
			
今天数据导入报错:Got a packet bigger than‘max_allowed_packet’bytes的问题 2个解决方法: 1.临时修改:mysql>set global max ...
 - 20155312 2016-2017-2《Java程序设计》课程总结
			
20155312 2016-2017-2<Java程序设计>课程总结 每周作业链接汇总 预备作业1:你期望的师生关系是什么? 预备作业2:做中学learning by doing个人感想 ...