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();

 

转载于:https://www.cnblogs.com/stardee/p/9623055.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值