首页 > 编程 > JavaScript > 正文

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

2019-11-19 13:23:05
字体:
来源:转载
供稿:网友

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 = 0loadingStatus$.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,请告诉我)

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表