UNPKG

ace-component

Version:

ace-components for ewms

139 lines (114 loc) 2.77 kB
import { Injectable } from '@angular/core'; import * as $ from 'jquery' export interface AjaxSetting { url: string; data?: any; headers?: any; body?: any; method: string; }; export interface CBparams { code: string; page: string; total: string; items: string; message?: string; } @Injectable() export class AceTableService { constructor( ) { }; private curAjax; toAjax({ url, setParams, cb, page, limit, cbParams }) { var parmams: any = setParams(); if (!setParams) { throw new Error('ace-table params is undefined'); } if (!parmams.method) { throw new Error('ace-table params method is undefined'); }; var self = this; if (parmams.url) { url = parmams.url; } var method = parmams.method.toLowerCase(); var options: any = { url, type: method, dataType: 'json', data: parmams.data, success: function (res) { let code = deepTraversal(res, cbParams.code) let items = deepTraversal(res, cbParams.items); let page = deepTraversal(res, cbParams.page) - 0; let total = deepTraversal(res, cbParams.total) - 0; let msg = deepTraversal(res, cbParams.message) cb({ code, items, page, total, msg, data: res }) }, error: function (err) { if (self.curAjax) { if (self.curAjax.statusText == 'abort') { } else { cb({ code: err.status, msg: err, data: err }) } } else { cb({ code: err.status, msg: '请求失败' }) } } }; if(parmams.withCredentials){ options.xhrFields = { withCredentials: true } options.crossDomain = true } if (parmams.headers) options.headers = parmams.headers; if (typeof parmams.data == 'string') { if (!options.headers['Content-Type']) { options.headers['Content-Type'] = 'application/json' } } else { parmams.data.pageNum = page; parmams.data.limit = limit;//改动 } if (this.curAjax && this.curAjax.status != 200) { this.curAjax.abort(); } this.curAjax = $.ajax(options); }; } function deepTraversal(parentObj, key) { var findOut = false; var target = undefined; handle(parentObj); return target; function handle(obj) { if (findOut) return if (typeof obj == 'object') { for (var i in obj) { if (i == key) { target = obj[i]; findOut = true; } else { if (typeof obj[i] == 'object') handle(obj[i]); } } } } }