ionic2实战ionic2

ionic2实战-自定义http拦截器

2017-02-26  本文已影响4519人  昵称已被使用_

2017年6月11日注:

本文的实现方式是代理了angular http,现在有一个轻量级的实现,只需一个ts文件,完整代码看这里
两种方式各有有点,各位自己斟酌,建议用轻量级的实现方式

为什么要http拦截器

直接上代码

import {NgModule, ErrorHandler} from '@angular/core';
import {IonicApp, IonicModule, IonicErrorHandler} from 'ionic-angular';
import {Storage} from '@ionic/storage';
import {MyApp} from './app.component';
import {LoginModule} from '../pages/login/login.module';
import {TabsPage} from '../pages/tabs/tabs';
import {ContactModule} from '../pages/contact/contact.module';
import {HomeModule} from '../pages/home/home.module';
import {MineModule} from '../pages/mine/mine.module';

import {NativeService} from "../providers/NativeService";
import {HttpIntercept} from "../providers/HttpIntercept";
import {HttpService} from "../providers/HttpService";
import {FileService} from "../providers/FileService";
import {Helper} from "../providers/Helper";
import {Utils} from "../providers/Utils";
import {TestModule} from "../pages/test/test.module";
import {Http, XHRBackend, RequestOptions} from "@angular/http";
import {HttpInterceptHandle} from "../providers/HttpInterceptHandle";


@NgModule({
  declarations: [MyApp, TabsPage],
  imports: [IonicModule.forRoot(MyApp, {
    backButtonText: '',
    iconMode: 'ios',
    modalEnter: 'modal-slide-in',
    modalLeave: 'modal-slide-out',
    pageTransition: 'ios'
  }), LoginModule, HomeModule, ContactModule, MineModule, TestModule],
  bootstrap: [IonicApp],
  entryComponents: [MyApp, TabsPage],
  providers: [HttpInterceptHandle, {provide: ErrorHandler, useClass: IonicErrorHandler},
    {
      provide: Http,
      useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, httpInterceptHandle: HttpInterceptHandle) => {
        return new HttpIntercept(backend, defaultOptions, httpInterceptHandle);
      },
      deps: [XHRBackend, RequestOptions, HttpInterceptHandle]
    },
    Storage, NativeService, HttpService, FileService, Helper, Utils]
})
export class AppModule {
}

app.module.ts完整代码
/**
 * Created by yanxiaojun617@163.com on 2-25.
 */
import {Events} from 'ionic-angular';
import {Injectable} from '@angular/core';
import {NativeService} from "./NativeService";

@Injectable()
export class HttpInterceptHandle {
  constructor(public events: Events, public nativeService: NativeService) {
    events.subscribe('request:before', (url, options) => {
      nativeService.showLoading();
      console.log('%c 请求前 %c', 'color:blue', '', 'url', url, 'options', options);
    });

    events.subscribe('request:success', (url, options, res) => {
      nativeService.hideLoading();
      console.log('%c 请求成功 %c', 'color:green', '', 'url', url, 'options', options, 'res', res);
    });

    events.subscribe('request:error', (url, options, error) => {
      nativeService.hideLoading();
      console.log('%c 请求失败 %c', 'color:red', '', 'url', url, 'options', options, 'error', error);
      let status = error.status;
      if (status === 0) {
        nativeService.showToast('请求响应错误,请检查网络');
      } else if (status === 404) {
        nativeService.showToast('请求链接不存在,请联系管理员');
      } else if (status === 500) {
        nativeService.showToast('服务器出错,请稍后再试');
      } else {
        nativeService.showToast('未知错误,请检查网络');
      }
    });
  }

}

`HttpInterceptHandle.ts`完整代码
/**
 * Created by yanxiaojun617@163.com on 12-27.
 */
import {Injectable} from '@angular/core';
import {Http, Response, RequestOptions, ConnectionBackend, RequestOptionsArgs} from '@angular/http';


import {Observable} from "rxjs";
import {HttpInterceptHandle} from "./HttpInterceptHandle";

@Injectable()
export class HttpIntercept extends Http {
  constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, public _: HttpInterceptHandle) {
    super(backend, defaultOptions);
  }

  get(url: string, options ?: RequestOptionsArgs): Observable < Response > {
    this._.events.publish("request:before", url, options);
    return Observable.create((observer) => {
      super.get(url, options).subscribe(res => {
        this._.events.publish("request:success", url, options, res);
        observer.next(res);
      }, err => {
        this._.events.publish("request:error", url, options, err);
        observer.error(err);
      });
    });
  }

  post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    this._.events.publish("request:before", url, options);
    return Observable.create((observer) => {
      super.post(url, body, options).subscribe(res => {
        this._.events.publish("request:success", url, options, res);
        observer.next(res);
      }, err => {
        this._.events.publish("request:error", url, options, err);
        observer.error(err);
      });
    });
  }

  put(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    this._.events.publish("request:before", url, options);
    return Observable.create((observer) => {
      super.put(url, body, options).subscribe(res => {
        this._.events.publish("request:success", url, options, res);
        observer.next(res);
      }, err => {
        this._.events.publish("request:error", url, options, err);
        observer.error(err);
      });
    });
  }

  delete(url: string, options ?: RequestOptionsArgs): Observable < Response > {
    this._.events.publish("request:before", url, options);
    return Observable.create((observer) => {
      super.delete(url, options).subscribe(res => {
        this._.events.publish("request:success", url, options, res);
        observer.next(res);
      }, err => {
        this._.events.publish("request:error", url, options, err);
        observer.error(err);
      });
    });
  }

  patch(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    this._.events.publish("request:before", url, options);
    return Observable.create((observer) => {
      super.patch(url, body, options).subscribe(res => {
        this._.events.publish("request:success", url, options, res);
        observer.next(res);
      }, err => {
        this._.events.publish("request:error", url, options, err);
        observer.error(err);
      });
    });
  }


  head(url: string, options ?: RequestOptionsArgs): Observable < Response > {
    this._.events.publish("request:before", url, options);
    return Observable.create((observer) => {
      super.head(url, options).subscribe(res => {
        this._.events.publish("request:success", url, options, res);
        observer.next(res);
      }, err => {
        this._.events.publish("request:error", url, options, err);
        observer.error(err);
      });
    });
  }


  options(url: string, options ?: RequestOptionsArgs): Observable < Response > {
    this._.events.publish("request:before", url, options);
    return Observable.create((observer) => {
      super.options(url, options).subscribe(res => {
        this._.events.publish("request:success", url, options, res);
        observer.next(res);
      }, err => {
        this._.events.publish("request:error", url, options, err);
        observer.error(err);
      });
    });
  }

}

`HttpInterceptHandle.ts`代码

测试

ionic2实战-自定义http拦截器.gif

最后

有个小问题需要修改一下app.module.ts,详情看这里
参考
源代码已上传到github

由于ionic版本更新较快,有些写法可能改变来不及更新简书,请以github代码为准

上一篇 下一篇

猜你喜欢

热点阅读