zoukankan      html  css  js  c++  java
  • 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){
    
      }
    }
  • 相关阅读:
    云架构师进阶攻略(3)
    微服务化之服务拆分与服务发现
    终于有人把云计算、大数据和人工智能讲明白了!(1)
    JavaScript的数组详解
    html中给元素添加背景图片或者gif动图
    JavaScript的事件
    JavaScript的匿名函数
    JavaScript获取和操作html的元素
    JavaScript的条件运算符与条件语句
    JavaScript变量、数据类型、函数
  • 原文地址:https://www.cnblogs.com/tomboyxiao/p/7550249.html
Copyright © 2011-2022 走看看