ajax.service.js 1.4 KB

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