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){

  }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM