RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
axios简单实现小程序延时loading指示

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

目前创新互联已为近1000家的企业提供了网站建设、域名、网页空间、网站托管、服务器托管、企业网站设计、秦都网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。

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

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

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

配合axios实现如下:

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

export const loadingStatus$: BehaviorSubject = new BehaviorSubject(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) => {
  if (res[0] !== res[1]) {
   return true
  } else {
   return false
  }
 }),
 map((res: Array) => {
  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,请告诉我)

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


分享题目:axios简单实现小程序延时loading指示
当前URL:http://sczitong.cn/article/jipghh.html