use-phone.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { login } from "../logic";
  2. import request from "../request/method";
  3. type Status = 'loading' | 'pending' | 'success' | 'fail'
  4. type UpdataStatusCallback = (status: Status) => void
  5. type UpdataValueCallback = (value: string) => void
  6. export function usePhoneNumber() {
  7. const _updataValue: UpdataValueCallback[] = [];
  8. const _updateStatus: UpdataStatusCallback[] = [];
  9. let value = '';
  10. let status: Status = 'loading';
  11. login(false).then(token => token ? 'pending' : 'fail' as const, () => 'fail' as const).then(_status => {
  12. status = _status;
  13. _updateStatus.forEach(cb => cb(status));
  14. })
  15. return {
  16. updateValue(callback: UpdataValueCallback) {
  17. _updataValue.push(callback);
  18. if (value) callback(value);
  19. },
  20. updateStatus(callback: UpdataStatusCallback) {
  21. _updateStatus.push(callback);
  22. callback(status)
  23. },
  24. getPhoneNumber(event: WechatMiniprogram.ButtonGetPhoneNumber, callback?: (value?: string) => void) {
  25. const code = event.detail.code;
  26. if (!code) return;
  27. _updateStatus.forEach(cb => cb('loading'))
  28. request({
  29. url: `/mobileAccountManage/getAccountPhone`,
  30. method: 'GET',
  31. params: { code },
  32. transform({ data }) { return data; }
  33. }).then(phone => {
  34. value = phone;
  35. status = 'success';
  36. if (typeof callback === 'function') callback(value)
  37. _updataValue.forEach(cb => cb(value))
  38. _updateStatus.forEach(cb => cb(status))
  39. }, (error) => {
  40. if (typeof callback === 'function') callback()
  41. _updateStatus.forEach(cb => cb('pending'))
  42. wx.showModal({ title: '获取失败', content: error.errMsg || error.message, showCancel: false })
  43. })
  44. }
  45. }
  46. }