ajax.service.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /**
  2. * ajax请求相关的服务
  3. */
  4. import ServiceUrl from './config.env'
  5. class AjaxService {
  6. constructor() {
  7. this.name = 'AjaxService'
  8. }
  9. getBaseUrl(url = '') {
  10. return url.indexOf('://') > -1 ? url : ServiceUrl + url
  11. }
  12. getHeaders({ header = {} }) {
  13. header['Accept'] = 'application/json'
  14. // header['Content-Type'] = 'application/x-www-form-urlencoded'
  15. header['Content-Type'] = 'application/json'
  16. return header
  17. }
  18. request(options = {}) {
  19. let header = this.getHeaders(options)
  20. let url = this.getBaseUrl(options.url)
  21. if (options.header) {
  22. header = Object.assign(header, options.header)
  23. }
  24. let { isLoading = true } = options
  25. if (isLoading) {
  26. wx.showLoading({ title: '加载中' })
  27. }
  28. const requestPromise = new Promise((resolve, reject) => {
  29. uni.request({
  30. url: url,
  31. method: options.method || 'POST',
  32. data: options.data || {},
  33. header,
  34. success: res => {
  35. if (isLoading) wx.hideLoading()
  36. if (options.isStatus) {
  37. resolve(res.data)
  38. } else {
  39. if (res.data.code === 0) {
  40. resolve(res.data)
  41. } else {
  42. reject(res.data)
  43. }
  44. }
  45. },
  46. fail: error => {
  47. reject(error)
  48. wx.hideLoading()
  49. }
  50. })
  51. })
  52. return requestPromise
  53. }
  54. get(options) {
  55. options.method = 'GET'
  56. return this.request(options)
  57. }
  58. post(options) {
  59. options.method = 'POST'
  60. return this.request(options)
  61. }
  62. }
  63. export default new AjaxService()