axios簡(jiǎn)單實(shí)現(xiàn)小程序延時(shí)loading指示
小程序和小游戲的wx.showLoading方法相信大家都不會(huì)陌生,但是怎樣處理loading才能又更好的用戶體驗(yàn)?zāi)兀?/p>
假設(shè)需求如下,1秒類請(qǐng)求沒(méi)有相應(yīng),才彈出loading,否則不彈出,請(qǐng)求錯(cuò)誤時(shí),彈出toast。
配合axios實(shí)現(xiàn)如下:
1.在狀態(tài)管理部分存儲(chǔ)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.在應(yīng)用啟動(dòng)時(shí)訂閱
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() } })
感覺(jué)配合rx,很多復(fù)雜功能都能很簡(jiǎn)單地實(shí)現(xiàn),另外這個(gè)功能會(huì)伴隨整個(gè)應(yīng)用周期,所以u(píng)nsbscribe可以不用太在意。(除非有其他的bad effect,請(qǐng)告訴我)
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com