Angular 2(Ionic 2):拦截ajax请求

时间:2016-03-04 17:35:00

标签: javascript angularjs ionic-framework angular ionic2

使用Angular 1.x可以使用某些代码拦截所有ajax请求:

$httpProvider.interceptors.push('interceptRequests');
...
var app_services = angular.module('app.services', []);
   app_services.factory('interceptRequests', [function () {
   var authInterceptorServiceFactory = {};
   var _request = function (config) {
   //do something here
   };
   var _responseError = function (rejection) {
   //do something here
   }
   authInterceptorServiceFactory.request = _request;
   authInterceptorServiceFactory.responseError = _responseError;
   return authInterceptorServiceFactory;
}]);

Angular 2中是否有类似(或开箱即用)的内容?

2 个答案:

答案 0 :(得分:6)

一种方法可以是扩展HTTP对象以拦截调用:

@Injectable()
export class CustomHttp extends Http {

  request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    console.log('request...');
    return super.request(url, options).catch(res => {
      // do something
    });        
  }

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    console.log('get...');
    return super.get(url, options).catch(res => {
      // do something
    });
  }
}

并按如下所述进行注册:

bootstrap(AppComponent, [HTTP_PROVIDERS,
    new Provider(Http, {
      useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions),
      deps: [XHRBackend, RequestOptions]
  })
]);

您可以利用catch运算符来捕获错误并在全局范围内处理错误......

请参阅此plunkr:https://plnkr.co/edit/ukcJRuZ7QKlV73jiUDd1?p=preview

答案 1 :(得分:-1)

请参阅此链接有关ionic2拦截器:http://roblouie.com/article/354/http-interceptor-in-angular-2/

1 - 覆盖Http标准类

import {Injectable} from "@angular/core";
import {Http, RequestOptionsArgs, ConnectionBackend, RequestOptions} from "@angular/http";
import {Observable} from "rxjs/Observable";
import {Request} from "@angular/http/src/static_request"
import {Response} from "@angular/http/src/static_response"

@Injectable()
export class CustomHttpInterceptor extends Http {

  constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
    super(backend, defaultOptions);
  }

  request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    console.log('My new request...');
    return super.request(url, options);
  }

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    console.log('My new get...');
    return super.get(url, options);
  }

  post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    console.log('My new post...');
    return super.post(url, body, options);
  }

}

2 - 注册提供商

export function providers() {
  return [
    Api,
    Items,
    User,
    Camera,
    GoogleMaps,
    SplashScreen,
    StatusBar,

    { provide: Settings, useFactory: provideSettings, deps: [Storage] },
    // Keep this to enable Ionic's runtime error handling during development
    { provide: ErrorHandler, useClass: IonicErrorHandler },
    {
      provide: Http,
      useFactory: (backend:XHRBackend, defaultOptions:RequestOptions) => {
        return new CustomHttpInterceptor(backend, defaultOptions);
      },
      deps: [XHRBackend, RequestOptions]
    }

  ];
}

@NgModule({
  declarations: declarations(),
  imports: [
    BrowserModule,
    HttpModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [Http]
      }
    }),
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot()
  ],
  bootstrap: [IonicApp],
  entryComponents: entryComponents(),
  providers: providers()
})
export class AppModule { }

3 - 只使用Http类,因为Custom Http Interceptor实例是自动注入的。

import { Page1 } from '../pages/page1/page1';
import { Page2 } from '../pages/page2/page2';

import { Http } from '@angular/http';

@Component({
  templateUrl: 'app.html'
})
export class MyAppComponent {
  @ViewChild('content') nav : Nav;

  root: any = Page1;

  constructor(public platform: Platform, private http: Http) {
    this.initializeApp();

    http.get('https://google.com');
  }
...