# 服务 `web-lib-services` web-lib-services 基于Axios封装的数据获取服务,简化和规范了拦截器的使用。 ## 使用 services 导出的工厂函数,你可以用来实例化一个扩展的axios实例。 ``` javascript import { Message } from 'element-ui' import WebLibServices from 'web-lib/packages/web-lib-services' import 'web-lib/packages/web-lib-services/lib/index.css' export const webLibServices = new WebLibServices() export default webLibServices ``` ## 拦截器 默认的service提供了缓存拦截器、全局加载指示器。 #### 缓存拦截器 缓存拦截器用于缓存请求结果或者缓存请求本身,缓存拦截器目前不会判断请求结果是否成功,即使请求报错也会进行缓存。 扩展了axios的config对象,通过在请求中对应的config配置对象来配置缓存拦截器。 - `config.cache` 为true时,将开启缓存。 - `config.promise` 是否缓存promise - `config.storage` 是否将缓存结果存储到storage中 - `config.timeout` 缓存超时时间 ### 全局加载指示器 全局加载指示器用于当发起请求时,显示全局的转圈和遮罩提示。 通过`config.globalLoading` 进行配置,默认为true所有请求都默认开启加载提示。 ### 自定义拦截器 你可以通过在实例化的时候传入一个拦截器对象列表。 ```js const service = new Service({ interceptors }) ``` `interceptors`是一个拦截器对象列表,你可以添加任意的拦截器。拦截器有两种类型:请求拦截器、响应拦截器。 一个拦截器对象需要包含以下属性: - `name` 用于方便维护,主要起注释作用。 - `type` 声明拦截器的类型,是请求拦截器(request) ,还是响应拦截器(response) - `onFulfilled` 拦截器成功回调 - `onRejected` 拦截器错误回调 拦截器默认按照列表顺序进行注入,如果有特殊需求,可以通过`enforce` 属性调整当前拦截器的顺序,可取值: - pre'当前拦截器优先执行 - normal 默认值,按照拦截器列表顺序执行 - post 当前拦截器延后执行 > 注:如果多个拦截器同时设置`enforce` 为 pre 或 post,则按照出现在拦截器列表的顺序优先或延后执行。 #### 请求拦截器 一般用于对请求头进行注入,或统一对请求数据进行去密操作等。 ```js { name: 'addRequestHeaderInterceptor', type: 'request', onFulfilled: config => { if (!config.headers['Content-Type']) { config.headers['Content-Type'] = 'application/json' } getToken() && (config.headers['token'] = getToken()) config.headers['scope'] = 1 return config }, onRejected: error => { return Promise.reject(error) }, } ``` #### 响应拦截器 一般用于对数据进行清洗或者统一的错误提示等。 ```js { name: 'errorMessageInterceptor', type: 'response', onFulfilled: response => response, onRejected: error => { const { response, config } = error Message({ message: response.data.msg || '请求失败,请重试', type: 'error', duration: 5 * 1000, }) return Promise.reject(error) }, } ```