axios簡單實現(xiàn)小程序延時loading指示
axios簡單實現(xiàn)小程序延時loading指示

小程序和小游戲的wx.showLoading方法相信大家都不會陌生,但是怎樣處理loading才能又更好的用戶體驗呢?
假設需求如下,1秒類請求沒有相應,才彈出loading,否則不彈出,請求錯誤時,彈出toast。
配合axios實現(xiàn)如下:
1.在狀態(tài)管理部分存儲loading狀態(tài)
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,很多復雜功能都能很簡單地實現(xiàn),另外這個功能會伴隨整個應用周期,所以unsbscribe可以不用太在意。(除非有其他的bad effect,請告訴我)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
在Vue中使用this.$store或者是$route一直報錯的解決
今天小編就為大家分享一篇在Vue中使用this.$store或者是$route一直報錯的解決,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
vue-cli history模式實現(xiàn)tomcat部署報404的解決方式
這篇文章主要介紹了vue-cli history模式實現(xiàn)tomcat部署報404的解決方式,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-09-09

