2016-03-04 60 views
1

具有角1.x中可以攔截與像一些代碼,所有Ajax請求:角2(離子型2):攔截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中?

回答

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

+0

這似乎是一個很好的實現。我嘗試過,但我使用CustomHttp中的get()方法時出現此錯誤:ORIGINAL EXCEPTION:TypeError:_get(...)。call(...)。catch不是函數 –

+1

@Chris您需要像這樣導入'catch'運算符:'import'rxjs/add/operator/catch' –

+0

現在這段代碼工作了(並從CustomHttp中移除了構造函數)。但現在我有其他錯誤:原始異常:TypeError:無法讀取包含函數XHRConnection(req,browserXHR,baseResponseOptions){... var _xhr = browserXHR.build(); –

-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 H ttp攔截器實例是自動注入的。

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'); 
    } 
... 
+1

歡迎您訪問解決方案的鏈接,但請確保您的答案在沒有它的情況下很有用:[添加鏈接的上下文](// meta.stackexchange.com/a/8259),以便您的同行用戶瞭解它是什麼以及爲什麼它在那裏,然後引用您鏈接的頁面中最相關的部分,以防目標頁面不可用。 [僅僅是一個鏈接的答案可能會被刪除。](// stackoverflow.com/help/deleted-answers) –