ajax.service.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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/json'
  15. return header
  16. }
  17. request(options = {}) {
  18. let header = this.getHeaders(options)
  19. let url = this.getBaseUrl(options.url)
  20. if (options.header) {
  21. header = Object.assign(header, options.header)
  22. }
  23. let { isLoading = true } = options
  24. if (isLoading) {
  25. uni.showLoading({ title: '加载中' })
  26. }
  27. const requestPromise = new Promise((resolve, reject) => {
  28. uni.request({
  29. url: url,
  30. method: options.method || 'POST',
  31. data: options.data || {},
  32. header,
  33. success: res => {
  34. if (isLoading) uni.hideLoading()
  35. if (options.isStatus) {
  36. resolve(res.data)
  37. } else {
  38. if (res.data.code === 0) {
  39. resolve(res.data)
  40. } else {
  41. reject(res.data)
  42. }
  43. }
  44. },
  45. fail: error => {
  46. reject(error)
  47. uni.hideLoading()
  48. }
  49. })
  50. })
  51. return requestPromise
  52. }
  53. get(options) {
  54. options.method = 'GET'
  55. return this.request(options)
  56. }
  57. post(options) {
  58. options.method = 'POST'
  59. return this.request(options)
  60. }
  61. }
  62. export default new AjaxService()