簡單封裝ajxa帶請求攔截功能
阿新 • • 發佈:2020-12-09
依賴Jquery,主要使用了jquery的$.Callbacks
'use strict' class Http { constructor() { this._init(); } _init() { this._initInterceptors(); } _initConfig(config) { this.defaultConfig = { async: true, method: 'GET', dataType: 'json' }; Object.assign(config, this.defaultConfig); } _initInterceptors() { const that = this; this.requestInterceptors = { done: $.Callbacks('once stopOnFalse'), fail: $.Callbacks('once stopOnFalse') } this.responseInterceptors = { done: $.Callbacks('once stopOnFalse'), fail: $.Callbacks('once stopOnFalse') } this.interceptors = { request:{ use: (success, fail)=>{ that._requestUse.call(that, success, fail); return that.interceptors.request; } }, response: { use: (success, fail)=>{ that._responseUse.call(that, success, fail); return that.interceptors.response; } } } } _addReuestToInterceptors(config) { console.log(this.requestInterceptors.done) this.requestInterceptors['done'].add( config =>{ this._realRequestFun(config); } ); this.requestInterceptors['done'].fire(config); } send(config) { this._initConfig(config); this._addReuestToInterceptors(config); } _requestUse(success, fail) { if (success != undefined && Object.prototype.toString.call(success) === '[object Function]') { this.requestInterceptors['done'].add(success); } if (fail != undefined && Object.prototype.toString.call(fail) === '[object Function]') { this.requestInterceptors['fail'].add(fail); } } _responseUse(success, fail) { if (success != undefined && Object.prototype.toString.call(success) === '[object Function]') { this.responseInterceptors['done'].add(success); } if (fail != undefined && Object.prototype.toString.call(fail) === '[object Function]') { this.responseInterceptors['fail'].add(fail); } } _realRequestFun(config) { const that = this; let deferred = $.Deferred(); $.when( that._await(deferred, config) ).done(res => { that.responseInterceptors['done'].fire(res); }).fail(err => { that.responseInterceptors['fail'].fire(err); }) } _await (deferred, config) { $.ajax(config) .done(data => { deferred.resolve(data); }) .fail(err => { deferred.reject(err); }) return deferred.promise(); } }
例子
let http = new Http(); http.interceptors.request.use(config =>{ console.log(1) },err =>{ console.log(err) }).use(config =>{ console.log(2) }) http.interceptors.response.use(data =>{ console.log("+++++++") console.log(data) console.log("+++++++") },err =>{ console.log(err) }) http.send({ type: "GET", url: "", dataType: 'json', data: { // } })
攔截函式返回的false將中斷攔截
let http = new Http();
http.interceptors.request.use(config =>{
console.log(1)
return false
},err =>{
console.log(err)
}).use(config =>{
console.log(2)
})
http.interceptors.response.use(data =>{
console.log("+++++++")
console.log(data)
console.log("+++++++")
console.log(err)
})
http.send({
type: “GET”,
url:"",
dataType: ‘json’,
data: {
//
}
})