ionic2+Angular 使用HttpInterceptorService拦截器 统一处理数据请求

sstep1:新建http-Interceptor.ts文件

import { Injectable } from '@angular/core';
import { HttpInterceptorService } from 'ng-http-interceptor';
import { Observable } from 'rxjs';
import { URLService } from './urls';
import { MsgBarService } from './msg-bar';

@Injectable()
export class HttpIntService {

    constructor(public httpservice: HttpInterceptorService, public urlservice: URLService, private ms: MsgBarService) {
        httpservice.request().addInterceptor((data, method, option) => {
            data[0] = this.urlservice.getUrl(data[0]);//地址拼接
            return data;
        })

        httpservice.response().addInterceptor(response => {
            return response.map(result => {
                var json = result.json();
                if (json.state && json.state.code == 200) {
                    return result;// 返回请求结果
                } else if (json.state && json.state.code == 600) {
                    //兑换商品是积分不足
                    //  return result;
                } else {
                    this.ms.showError(json.state.msg);//统一处理返回的提示信息
                }
                // //返回状态
                throw json.state.msg;
}).
catch(error => { if (typeof error === 'string') { this.ms.showError(error); } else if (error != response) { response.subscribe(p => { this.ms.showError('服务器发生错误'); }) } else { this.ms.showError('服务器发生错误'); } return Observable.throw(error) }) }) } }

 

step2:在app.module.ts文件中添加HttpIntService,并且在构造器中添加。

@NgModule({
  declarations: [
    MyApp,
    TabsPage,
  ],
  imports: [
    BrowserModule,
    HttpModule,
    HttpInterceptorModule,
    IonicModule.forRoot(MyApp,{
      backButtonText:'',
      backButtonIcon:'jf-arrow-back',//自定义返回按钮图标
      iconMode:'ios',//统一图标样式
      mode: 'ios',//Android和iOS模式统一
      menuType:'reveal',
      pageTransition:'ios-transition',
      tabsHideOnSubPages:true,
      preloadModules: true
    })
  ],
  bootstrap: [IonicApp],
  entryComponents: [],
  providers: [
    StatusBar,
    SplashScreen,
    HttpIntService,
    URLService,
    HttpInterceptorService,
    WechatService,
    { provide: ErrorHandler, useClass: IonicErrorHandler }
  ]
})

export class AppModule {
  constructor(_:HttpIntService){

  }
}

 

posted @ 2017-09-19 10:55  吃童话的小马  阅读(2576)  评论(0编辑  收藏  举报