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,請告訴我)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答