ionic3——页面多http请求失败时,跳转到失败页面

我的做法:

本来想用rxjs的forkjoin方法,但是调试失败。于是就捣鼓在请求服务页设置一个全局变量来判断,具体如下。

1.设置全局变量

2.因为我请求方式是公用的,封装了get和post

get请求封装:

/**
   * get 请求
   * @param path 接口字符串
   * @param params  参数
   */
  public get(path: string , params?:object): Observable<Res> {
    let url = `${APP_SERVE_URL}${path}`;
    return Observable.create((observer) => {
      this.http
        .get(url, {headers: this.headers,params:params})
        .map(res=>res.json())
        .subscribe(data => {
          if(data.errorCode!="-1"){
            this.passedToken(data);
          }else{
              observer.next(data);
          }
        }, err => {
          this.requestFailed(err);//处理请求失败
          observer.error(err);
        });
    });
  }

post请求封装:

/**
   * post 请求
   * @param path  接口
   * @param options 接口参数  
   */
  public post(path: string, options: any = null): Observable<Res> {
    let url = `${APP_SERVE_URL}${path}`;
    return Observable.create((observer) => {
      this.http
      .post(url, options, { headers: this.headers })
      .map(res=>res.json())
      .subscribe(data => {
        
        if(data.errorCode!="-1"){
          this.passedToken(data);
        }else{
            observer.next(data);
        }
      }, err => {
        
        this.requestFailed(err);//处理请求失败
        observer.error(err);
      });
    });
  }

其中,passedToken方式是在请求成功返回的token过期处理。

/**
   * token 过期
   * @param err 
   */
  passedToken(JsonData){
    this.nativeService.showToast(JsonData.msg,2000);
    setTimeout(()=>{
      if(JsonData.errorCode!="0"){
        let activeNav: NavController = this.appCtrl.getActiveNav();
        activeNav.push("LoginPage");
      }
    },2000);
  }

3.requestFailed方法是请求失败的执行程序

 /**
   * 处理请求失败事件
   */
  private requestFailed(err) {
    let msg = '请求发生异常', status = err.status;
    if (!this.nativeService.isConnecting()) {
      msg = '连接不上网络,请检测网络';
    } else {
      if (status === 0) {
        msg = '请求失败,请求响应出错';
      } else if (status === 404) {
        msg = '请求失败,未找到请求地址';
      } else if (status === 500) {
        msg = '请求失败,服务器出错,请稍后再试';
      }
    }
    //当第一次请求this.httpErrPage==""时,进入失败页面
    //当页面变化,请求失败时,进入失败页面
    if(this.httpErrPage=="" || this.httpErrPage !=this.utils.getPageName()){
      let activeNav: NavController = this.appCtrl.getActiveNav();
      const lastpage = this.utils.getPageName();
      activeNav.push("NotNetPage",{
        msg:msg,
        lastpage:lastpage
      });
    }
    this.httpErrPage = this.utils.getPageName();
    
    /* this.alertCtrl.create({
      title: msg,
      subTitle: status,
      buttons: [{ text: '确定' }]
    }).present(); */
  }

//当第一次请求this.httpErrPage==""时,进入失败页面

//当页面变化,请求失败时,进入失败页面

if(this.httpErrPage=="" || this.httpErrPage !=this.utils.getPageName()) 

这个条件就是用来处理一个页面多个请求都失败的情况,只有第一次切换到失败页面。

猜你喜欢

转载自blog.csdn.net/assassin_0302/article/details/87913618