Angular 2 (Ionic 2): intercept ajax requests

2019-07-28 20:08发布

With Angular 1.x is possible to intercept all ajax requests with some code like:

$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;
}]);

Is there anything similar (or out-of-the-box) in Angular 2?

2条回答
【Aperson】
2楼-- · 2019-07-28 20:52

See this link about ionic2 interceptors: http://roblouie.com/article/354/http-interceptor-in-angular-2/

1 - Override Http standard class

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 - Register provider

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 - And just use Http class, because the Custom Http Interceptor instance is injected automatically.

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');
  }
...
查看更多
淡お忘
3楼-- · 2019-07-28 20:54

An approach could be to extend the HTTP object to intercept calls:

@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
    });
  }
}

and register it as described below:

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

You can leverage for example the catch operator to catch errors and handle them globally...

See this plunkr: https://plnkr.co/edit/ukcJRuZ7QKlV73jiUDd1?p=preview.

查看更多
登录 后发表回答