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

网络编程 2021-07-04 16:46www.168986.cn编程入门
这篇文章主要介绍了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,请告诉我)

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

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by

长沙网络推广|微博营销|长沙seo优化|视频营销|长沙网络营销|微信营销|长沙网站建设|口碑营销|软文营销