rxjs处理http请求超时


博客原文地址

使用场景

用户进行一个操作请求后台而长时间未响应,我们希望给用户一个信息展示(请求超时,网络不好…).

RxJS实现

关于RxJS请看这里

我这个功能的实现主要使用 delayrace两个操作符。
* 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();

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM