使用場景
用戶進行一個操作請求后台而長時間未響應,我們希望給用戶一個信息展示(請求超時,網絡不好…).
RxJS實現
關於RxJS請看這里
我這個功能的實現主要使用 delay,race兩個操作符。
* delay 通過給定的超時或者直到一個給定的時間來延遲源 Observable 的發送。延遲時間(以毫秒為單位的數字)或 Date 對象(發送延遲到這個時間點)。
* race 返回 Observable,該 Observable 是源 Observable 和提供的 Observables 的組合中 第一個發出項的 Observable 的鏡像。
具體實現過程代碼(使用angualr和ionic)如下:
我封裝成了service方便使用。主要看timeoutDeal方法。
service.ts
import { Injectable } from "@angular/core";
import { delay, map, race } from "rxjs/operators";
import { Observable } from "rxjs/Observable";
import { AlertController, LoadingController } from "ionic-angular";
@Injectable()
export class HttpTimeoutService {
loading: any;
timer: any;
timers:any[]=[];
constructor(private loadingCtrl: LoadingController,
private alertCtrl: AlertController) {
}
// **參數name和參數mes相同
showLoading(name) {
const self = this;
let obj={name:name,timer:undefined,loading:undefined};
const timer = setTimeout(() => { let loading = this.loadingCtrl.create(); loading.present(); obj.loading=loading; }, 500); obj.timer=timer; this.timers.push(obj); } clearTimer(name) { const self = this; for(let i=0;i<this.timers.length;i++){ if(this.timers[i].name===name){ if(this.timers[i].loading){ this.timers[i].loading.dismiss(); } clearTimeout(this.timers[i].timer); this.timers.splice(i,1); return; } } } timeoutDeal(mes) { const self = this; let TIME_OUT = 6000; let cancel$ = Observable.of(null).pipe(delay(TIME_OUT), map(_ => { // throw 'error'; self.clearTimer(mes); self.alertCtrl.create({ title: '連接超時', message: '當前網絡不穩定,請尋找一個穩定網絡!', buttons: ['確定'] }).present(); throw mes + 'timeout!' // 重要 })); return cancel$; } }
pipe是 Observable 中有一個內置的 pipe 方法 (Observable.prototype.pipe),它可以用類似於之前的鏈式調用的方式來組合操作符。RxJS 5.5版本之后。
使用:
... import 'rxjs/add/operator/race'; import 'rxjs/add/operator/delay'; export class HomePage extends BasePage { ... constructor( private httpTimeoutService: HttpTimeoutService, private smartSellerHomepageService: SmartSellerHomepageServiceProxy, .... this.httpTimeoutService.showLoading('getFirstPageInfo'); this.smartSellerHomepageService.getFirstPageInfo(moment()) .race(this.httpTimeoutService.timeoutDeal('getFirstPageInfo')) .subscribe(res => { this.httpTimeoutService.clearTimer('getFirstPageInfo'); // console.log(res); this.firstPageInfo = res; }, error => { }, ()=>{ this.httpTimeoutService.clearTimer('getFirstPageInfo'); ); ...
```````11月28日更新````````
最近新項目中使用rxjs版本是v6以上
Observable.of的用法改了使用
import { of } from 'rxjs'
race 最好的用法:
import { race } from 'rxjs'
race($a, $b).subscribe();
