Python语言技术文档

微信小程序技术文档

php语言技术文档

jsp语言技术文档

asp语言技术文档

C#/.NET语言技术文档

html5/css技术文档

javascript

点击排行

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

来源:中文源码网    浏览:438 次    日期:2024-04-27 01:57:14
【下载文档:  axios简单实现小程序延时loading指示.txt 】


axios简单实现小程序延时loading指示
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,请告诉我)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持中文源码网。

相关内容