首页 > 编程开发 > JavaScript    日期:2020-05-27 / 浏览

axios简单实现小程序延时loading指示

axios简单实现小程序延时loading指示

小程序和小游戏的wx.showLoading方法相信大家都不会陌生,但是怎样处理loading才能又更好的用户体验呢?

假设需求如下,1秒类请求没有相应,才弹出loading,否则不弹出,请求错误时,弹出toast。

配合axios实现如下:

1.在状态管理部分存储loading状态

export const loadingStatus$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false)

axios.interceptors.request.use(
 (config: any) => {
  loadingStatus$.next(true)
  return config
 },
 (error: any) => {
  return Promise.reject(error)
 },
)

axios.interceptors.response.use(
 (response: any) => {
  loadingStatus$.next(false)
  return response.data
 },
 (error: any) => {
  loadingStatus$.next(false)
  wx.showToast({ title: 'something wrong happened, please try it later' })
  return Promise.reject(error)
 },
)

2.在应用启动时订阅

let timer: any = 0
loadingStatus$
.pipe(
 pairwise(),
 filter((res: Array<boolean>) => {
  if (res[0] !== res[1]) {
   return true
  } else {
   return false
  }
 }),
 map((res: Array<boolean>) => {
  return res[1]
 }),
)
.subscribe((res: boolean) => {
 // once changed, value must be distinct
 if (timer === 0) {
  timer = setTimeout(() => {
   wx.showLoading({ title: 'loading...' })
  }, 1000)
 } else {
  clearTimeout(timer)
  timer=0
  wx.hideLoading()
 }
})

感觉配合rx,很多复杂功能都能很简单地实现,另外这个功能会伴随整个应用周期,所以unsbscribe可以不用太在意。(除非有其他的bad effect,请告诉我)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

觉得上面的内容有用吗?快来点个赞吧!

点赞() 我要打赏

温馨提示 : 本站内容来自会员投稿以及互联网,所有源码及教程均为作者总结编辑,请大家在使用过程中提前做好备份,以免发生无法预知的错误,源码类教程请勿直接用于生产环境!

 可能感兴趣的文章